您可以使用jquery插件“onscreen”在滚动时检查元素是否在当前视图中。
当选择器出现在屏幕上时,插件将选择器的“:on screen”设置为true。
这是插件的链接,可以包含在项目中。
“
http://benpickles.github.io/onScreen/jquery.onscreen.min.js
“
你可以试试下面这个对我有用的例子。
$(document).scroll(function() {
if($("#div2").is(':onScreen')) {
console.log("Element appeared on Screen");
//do all your stuffs here when element is visible.
}
else {
console.log("Element not on Screen");
//do all your stuffs here when element is not visible.
}
});
HTML代码:
<div id="div1" style="width: 400px; height: 1000px; padding-top: 20px; position: relative; top: 45px"></div> <br>
<hr /> <br>
<div id="div2" style="width: 400px; height: 200px"></div>
CSS:
#div1 {
background-color: red;
}
#div2 {
background-color: green;
}