JQuery:当元素在视图中时触发动作 [英] JQuery: fire action when element is in view

查看:272
本文介绍了JQuery:当元素在视图中时触发动作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:

   <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的东西,但找不到一个工作的解决方案...谢谢!

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!

推荐答案

有一个简单的检查,看看是否或者没有元素在视口中。

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

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

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

<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 ,它允许视口选择器,您的代码将如下所示:

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

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

这篇关于JQuery:当元素在视图中时触发动作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆