[英]Trigger jQuery function only when in viewport?
我的網站上有這個簡單的 jQuery 計數器。 我面臨的唯一問題是,在您到達嵌入 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/ 8810583844588 插件: https://github.com/zeusdeux/在視口中
將 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. 只需使用 class 而不是選擇器#number1, #number2
等,這樣您的代碼就更干凈了,想象一下#number99
的未來。 2. 計數器應該停留在上次離開的地方還是重置?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.