如何解决仅在视口中触发jQuery函数?
我的网站上有这个简单的jQuery Counter。我所面临的唯一问题是,在进入html代码嵌入部分之前,计数器已经开始或者甚至已经结束。
非常感谢您的帮助!
<script>
var isInViewport = function(elem) {
var distance = elem.getBoundingClientRect();
return (distance.top >= 0 && distance.left >= 0 && distance.bottom <= (window.innerHeight || document.documentElement.clientHeight) && distance.right <= (window.innerWidth || document.documentElement.clientWidth));
}
// then in your code ..
if(isInViewPort) {
$.fn.jQuerySimpleCounter = function( options ) {
var settings = $.extend({
start: 0,end: 100,easing: 'swing',duration: 400,complete: ''
},options );
var thisElement = $(this);
$({count: settings.start}).animate({count: settings.end},{
duration: settings.duration,easing: settings.easing,step: function() {
var mathCount = Math.ceil(this.count);
thisElement.text(mathCount);
},complete: settings.complete
});
};
$('#number1').jQuerySimpleCounter({end: 52,duration: 5000});
$('#number2').jQuerySimpleCounter({end: 35,duration: 3000});
$('#number3').jQuerySimpleCounter({end: 998,duration: 6000});
}</script>
解决方法
有多种方法
香草JS:https://gomakethings.com/how-to-test-if-an-element-is-in-the-viewport-with-vanilla-javascript/ jQuery插件:https://github.com/zeusdeux/isInViewport
已更新 Vanilla版本作为伪代码用于定向用途-可以进行极大地优化。
var isInViewport = function(elem) {
var distance = elem.getBoundingClientRect();
return (distance.top >= 0 && distance.left >= 0 && distance.bottom <= (window.innerHeight || document.documentElement.clientHeight) && distance.right <= (window.innerWidth || document.documentElement.clientWidth));
}
$.fn.jQuerySimpleCounter = function( options ) {
var settings = $.extend({
start: 0,end: 100,easing: 'swing',duration: 400,complete: ''
},options );
var thisElement = $(this);
$({count: settings.start}).animate({count: settings.end},{
duration: settings.duration,easing: settings.easing,step: function() {
var mathCount = Math.ceil(this.count);
thisElement.text(mathCount);
},complete: settings.complete
});
}
function startCounters() {
if(isInViewport($('#number1').get(0))) $('#number1').jQuerySimpleCounter({end: 52,duration: 5000});
if(isInViewport($('#number2').get(0))) $('#number2').jQuerySimpleCounter({end: 52,duration: 5000});
if(isInViewport($('#number3').get(0))) $('#number3').jQuerySimpleCounter({end: 52,duration: 5000});
}
$(document).ready(function(){
startCounters()
})
$(window).on("scroll",function(){
startCounters()
})
您可以通过以下更新进行改进
1.不用选择器#number1,#number2
等,而只是使用一个类,这样您的代码就更干净了,想象一下#number99
的未来。
2.计数器应该停在最后离开的地方还是可以重置?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。