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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23222131/
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-08-27 02:12:59  来源:igfitidea点击:

JQuery: fire action when element is in view

jqueryeventsdomvisible

提问by MarcL

In the footer of my site I'm using counUp.js (Link: http://inorganik.github.io/countUp.js/) to count up three numbers. I added this code at the bottom of the site:

在我网站的页脚中,我使用 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>

This works well, but starts counting once the page is loaded of course. How do I manage to fire this effect when the containing div of the numbers is 'in view' and not when the page is loaded? Tried several jQuery things but can't find a working solution... Thanks!

这很有效,但当然在页面加载后开始计数。当数字的包含 div 处于“可见”状态而不是页面加载时,我如何设法触发这种效果?尝试了几个 jQuery 的东西,但找不到有效的解决方案......谢谢!

回答by Adjit

There is a simple check to see whether or not an element is in the viewport.

有一个简单的检查来查看元素是否在视口中。

You can choose either to use a plugin or pure JQuery.

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

Relevant HTML :

相关 HTML :

<div id="inViewport">Is this in the viewport?</div>

Pure JQuery :

纯 JQuery :

Here is the fiddle for this : http://jsfiddle.net/zWtkc/1/

这是这个的小提琴: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
        }
    });
});

Plugins :

插件:

You can use this plugin : https://github.com/teamdf/jquery-visible/

你可以使用这个插件: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
    }
});

Or you can use this plugin : http://www.appelsiini.net/projects/viewportwhich allows for viewport selectors and your code will look like this :

或者你可以使用这个插件:http: //www.appelsiini.net/projects/viewport它允许视口选择器,你的代码看起来像这样:

$('#inViewport:in-viewport').doSomething();

回答by Chris Landsheere

This is how I did it using this plugin: https://github.com/protonet/jquery.inview

这就是我使用这个插件的方式: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();
});

回答by ahmed

Here is my code to run a function when element start getting into the view port.

这是我在元素开始进入视口时运行函数的代码。



您可以通过单击查看正在运行的代码 jfiddle小提琴

var counterTeaserL = $('.go-counterTeaser');
var winHeight = $(window).height();
if (counterTeaserL.length) {
    var firEvent = false,
        objectPosTop = $('.go-counterTeaser').offset().top;

        //when element shows at bottom
        var elementViewInBottom = objectPosTop - winHeight;
    $(window).on('scroll', function() {
        var currentPosition = $(document).scrollTop();
        //when element position starting in viewport
      if (currentPosition > elementViewInBottom && firEvent === false) {
        firEvent = true;
        animationCounter();
      }   
    });
}

//counter function will animate by using external js also add seprator "."
 function animationCounter(){
        $('.numberBlock h2').each(function () {
            var comma_separator_number_step =           $.animateNumber.numberStepFactories.separator('.');
            var counterValv = $(this).text();
            $(this).animateNumber(
                {
                  number: counterValv,
                  numberStep: comma_separator_number_step
                }
            );
        });
    }


https://jsfiddle.net/uosahmed/frLoxm34/9/