【问题标题】:How to launch javascript counter with calculations when my text is in viewport?当我的文本在视口中时,如何使用计算启动 javascript 计数器?
【发布时间】:2018-06-26 15:39:06
【问题描述】:

我有一个带有计数器的页面,它每天将一个数量加 8,此外我还需要从零开始倒计时。我已经解决了这些问题,但问题是计数器在页面加载时启动,而不是在文本在视口上时启动。我该如何解决?我找到了一些功能,但我无法实现它们:(这是我在 html 块中的代码:

<!DOCTYPE html>
<html>
<body>

<p class="Count" id="uno"></p>  

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> . 
</script>

<script>
var startDate1 = new Date(1522645200000)
var today1 = new Date();
var diff1 = Math.floor((today1 - startDate1)/(86400000))
var answer1 = 5600 + diff1 * 8

document.getElementById("uno").innerHTML = answer1;


$('.Count').each(function () {
 var $this = $(this);
 jQuery({ Counter: 0 }).animate({ Counter: $this.text() }, {
   duration: 1000,
   easing: 'swing',
   step: function () {
      $this.text(Math.ceil(this.Counter));
    }
  });
});


</script>

</body>
</html>

这是JS Bin,您可以在其中查看正在执行的代码。

【问题讨论】:

标签: javascript jquery html counter viewport


【解决方案1】:

这里是检查标题是否在 ViewPort 中的代码

window.addEventListener('scroll', function () {
   var inViewPortBol = inViewPort();
   //if true means, you element invieport, the call you counterAnimation
});
function inViewPort() {
        var arentLocal = yourTitleElement.getBoundingClientRect();
        return parentLocal.bottom > 0 &&
            parentLocal.right > 0 &&
            parentLocal.left < (window.innerWidth || document.documentElement.clientWidth) &&
            parentLocal.top < (window.innerHeight || document.documentElement.clientHeight);
}

让我知道它是否有帮助。 谢谢!

【讨论】:

    猜你喜欢
    • 2022-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多