每页多个视口检查

问题描述 投票:2回答:1

我正在使用脚本来计算从0到实际值的数字。要启动计数器,我希望元素位于视口的可见区域。

我找到了一个解决方案来检查元素是否在可见区域。但是,如果我在页面的不同区域使用多个数字元素,那么这不起作用。它计算具有相同类的每个元素(.counter)。

如果我使用不同名称的计数器脚本两次,第二个版本不起作用,第一个版本不能用于滚动。只有我在pageload的可见区域有计数器。

这是我的柜台代码:

$('.counter').each(function() {
    var $this = $(this),
    countTo = $this.attr('data-count');

    $({ countNum: $this.text()}).animate({
        countNum: countTo
    },

    {
        duration: 2000,
        easing:'linear',
        step: function() {
            $this.text(Math.floor(this.countNum));
        },
        complete: function() {
            $this.text(this.countNum);
        }

    });

});

这是我尝试的解决方案(每页工作一次):https://stackoverflow.com/a/488073/1788961

在这里,您可以找到整个代码的小提琴:https://codepen.io/cray_code/pen/QYXVWL

这是检查我是否滚动到元素的代码(参见上面的链接答案):

function isScrolledIntoView(elem)
{
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();

    var elemTop = $(elem).offset().top;
    var elemBottom = elemTop + $(elem).height();

    return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}


function Utils() {

}

Utils.prototype = {
    constructor: Utils,
    isElementInView: function (element, fullyInView) {
        var pageTop = $(window).scrollTop();
        var pageBottom = pageTop + $(window).height();
        var elementTop = $(element).offset().top;
        var elementBottom = elementTop + $(element).height();

        if (fullyInView === true) {
            return ((pageTop < elementTop) && (pageBottom > elementBottom));
        } else {
            return ((elementTop <= pageBottom) && (elementBottom >= pageTop));
        }
    }
};

var Utils = new Utils();
javascript jquery counter viewport
1个回答
2
投票

您检查isElementInView一次,而不是单独检查每个元素。当然它启动所有计数器。

var isElementInView = Utils.isElementInView($('.counter'), false);
if (isElementInView) {
            $('.counter').each(function() {

将它移到.each函数内部,它将分别用于每个计数器。

$('.counter').each(function() {
                var $this = $(this),
                countTo = $this.attr('data-count');
                var isElementInView = Utils.isElementInView($this, false);
                if (isElementInView) {
                // do animation

如果您希望在滚动时发生这种情况,则需要在每次滚动时向执行代码的页面添加EventListener:https://developer.mozilla.org/en-US/docs/Web/Events/scroll

function checkForVisible(){
    $('.counter').each(function() {
                var $this = $(this),
                countTo = $this.attr('data-count');
                var isElementInView = Utils.isElementInView($this, false);
                if (isElementInView) {
                // etc code
}

var ticking = false;
window.addEventListener('scroll', function(e) {
  if (!ticking) {
    window.requestAnimationFrame(function() {
      checkForVisible();
      ticking = false;
    });
    ticking = true;
  }
});
© www.soinside.com 2019 - 2024. All rights reserved.