JQuery:当元素在视图中时触发动作

在我网站的页脚中,我使用counUp.js(链接: http ://inorganik.github.io/countUp.js/)来计算三个数字。 我在网站底部添加了此代码:

 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(); }  

这很好用,但当然加载页面后开始计数。 如果数字的包含div是“在视图中”而不是在加载页面时,如何设置触发此效果? 尝试了几个jQuery的东西,但找不到工作的解决方案……谢谢!

可以通过简单的检查来查看元素是否在视口中。

您可以选择使用插件或纯JQuery。

相关HTML:

 
Is this in the viewport?

纯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(); 

这就是我使用这个插件的方式: https : //github.com/protonet/jquery.inview

 var options = { useEasing : true, useGrouping : true, separator : ',', decimal : '.', prefix : '', suffix : '' }; var c1 = new CountUp("a1", 0, 1000, 0, 5, options); var c2 = new CountUp("a2", 0, 1000, 0, 5, options); var c3 = new CountUp("a3", 0, 1000, 0, 5, options); var c4 = new CountUp("a4", 0, 1000, 0, 5, options); var c5 = new CountUp("a5", 0, 1000, 0, 5, options); var c6 = new CountUp("a6", 0, 1000, 0, 5, options); $('#counters').one('inview', function(event, isInView) { c1.start(); c2.start(); c3.start(); c4.start(); c5.start(); c6.start(); });