在我网站的页脚中,我使用 counUp.js (链接:http://inorganik.github.io/countUp.js/) 来计算三个数字。我在网站底部添加了这段代码:
<script type="text/javascript">
var c1 = new countUp("upnum1", 1, 27, 0, 4);
var c2 = new countUp("upnum2", 1, 10, 0, 4);
var c3 = new countUp("upnum3", 1, 27, 0, 4);
var c4 = new countUp("upnum4", 1, 1000, 0, 4);
window.onload = function() {
c1.start();
c2.start();
c3.start();
c4.start();
}
</script>
这效果很好,但当然,一旦页面加载就开始计数。当包含数字的 div 处于“视图中”而不是在加载页面时,如何设法触发此效果?尝试了一些 jQuery 的东西,但找不到有效的解决方案...谢谢!
有一个简单的检查来查看元素是否在视口中。
您可以选择使用插件或纯 JQuery。
相关 HTML :
<div id="inViewport">Is this in the viewport?</div>
纯 JQuery :
这是这个的小提琴:http://jsfiddle.net/zWtkc/1/
$.fn.isOnScreen = function(){
var win = $(window);
var viewport = {
top : win.scrollTop(),
left : win.scrollLeft()
};
viewport.right = viewport.left + win.width();
viewport.bottom = viewport.top + win.height();
var bounds = this.offset();
bounds.right = bounds.left + this.outerWidth();
bounds.bottom = bounds.top + this.outerHeight();
return (!(viewport.right < bounds.left || viewport.left > bounds.right || viewport.bottom < bounds.top || viewport.top > bounds.bottom));
};
$(document).ready(function(){
$(window).scroll(function(){
if ($('#inViewport').isOnScreen()) {
// The element is visible, do something
alert("in viewport!");
} else {
// The element is NOT visible, do something else
}
});
});
插件:
你可以使用这个插件:https://github.com/teamdf/jquery-visible/
$(document).ready(function(){
if ($('#inViewport').visible(true)) {
// The element is visible, do something
} else {
// The element is NOT visible, do something else
}
});
或者你可以使用这个插件:http://www.appelsiini.net/projects/viewport它允许使用视口选择器,您的代码将如下所示:
$('#inViewport:in-viewport').doSomething();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)