javascript 当元素出现在屏幕上时如何开始动画?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26667562/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 06:17:38  来源:igfitidea点击:

How to start animations when element appears on screen?

javascriptjquerycssanimation

提问by Matrix

How is an HTML element animated as soon as it appears on screen?

HTML 元素一出现在屏幕上如何动画?

I found an example on the stack overflow tour page, where info elements slide into the page as soon as you scroll down far enough. What is the trick behind that?

我在堆栈溢出游览页面上找到了一个示例,只要向下滚动到足够远的位置,信息元素就会滑入页面。这背后的诀窍是什么?

采纳答案by DreamTeK

You need to use javascript to detect the location of the viewport and activate it when it becomes visible.

您需要使用 javascript 来检测视口的位置并在它可见时激活它。

You can use javascript to detect and execute the transition and then css or javascript to do the animations.

您可以使用 javascript 来检测和执行过渡,然后使用 css 或 javascript 来制作动画。

There are many jquery based scripts available to accomplish this. Here is one example:

有许多基于 jquery 的脚本可用于完成此任务。这是一个例子:



DEMO

演示



1.Create an Html element you wan to check if it's in the viewport.

1.创建一个 Html 元素来检查它是否在视口中。

<div class="demo"></div>

2.Load the jQuery javascript library and jQuery Viewport Checker plugin at the end of your document.

2.在文档末尾加载 jQuery javascript 库和 jQuery Viewport Checker 插件。

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="viewportchecker.js"></script>

3.Call the plugin on this element and do something in the javascript.

3.在这个元素上调用插件并在javascript中做一些事情。

<script>
$(document).ready(function(){
$('.demo').viewportChecker({
// Class to add to the elements when they are visible
classToAdd: 'visible',

// The offset of the elements (let them appear earlier or later)
offset: 100,

// Add the possibility to remove the class if the elements are not visible
repeat: false,

 // Callback to do after a class was added to an element. Action will return "add" or "remove", depending if the class was added or removed
callbackFunction: function(elem, action){}
});
});
</script>


DOWNLOAD THIS SCRIPT

下载这个脚本