我试图将一个类添加到位于视口(viewport)中的元素中。我已经实现了这一点,但是当我滚动时,它会导致我的网站性能出现严重问题。
我目前有这个 JavaScript:
//Cache reference to window and animation items
var $animation_elements = $('.animation-element');
var $window = $(window);
$window.on('scroll resize', check_if_in_view);
$window.trigger('scroll');
function check_if_in_view() {
var window_height = $window.height();
var window_top_position = $window.scrollTop();
var window_bottom_position = (window_top_position + window_height);
$.each($animation_elements, function() {
var $element = $(this);
var element_height = $element.outerHeight();
var element_top_position = $element.offset().top;
var element_bottom_position = (element_top_position + element_height);
//check to see if this current container is within viewport
if ((element_bottom_position >= window_top_position) &&
(element_top_position <= window_bottom_position)) {
$element.addClass('in-view');
} else {
$element.removeClass('in-view');
}
});
}
正如您所看到的,check_if_in_view()
函数似乎在页面滚动时不断触发,我相信这可能是性能如此糟糕的原因。
是否有更有效的方法在滚动页面时添加类,并且不会导致我的网站出现性能问题?
最佳答案
使用 setTimeout
来延迟每次触发 scroll
事件时调用该函数。在下面的代码(我借用 from Codrops )中,设置了一个标志,以便在连续滚动的情况下每 60 毫秒调用该函数。
function Scroller(el) {
this.elements = Array.prototype.slice.call( el );
this._init();
}
Scroller.prototype = {
_init : function() {
//this flag prevents that the function _scrollPage is called
//every time the 'scroll' event is fired
this.didScroll = false;
window.addEventListener( 'scroll', this._scrollHandler.bind(this), false );
},
_scrollHandler : function() {
if( !this.didScroll ) {
this.didScroll = true;
setTimeout( function() { this._scrollPage(); }, 60 );
}
},
_scrollPage : function() {
this.elements.forEach( function( el, i ) {
if( inViewport(el) ) {
classie.add( el, 'i-am-in-the-viewport' );
}
else {
classie.remove( el, 'i-am-in-the-viewport' );
}
});
this.didScroll = false;
}
};
要使用它,请调用 new Scroller( document.getElementsByClassName('elements-to-watch') );
。
查看 Codrops 上的完整代码,了解 inViewPort()
函数的实现。 Classie.js用于处理类名的分配。
如果有不明白的地方,不要害怕要求澄清!
关于javascript - 检测 View 中的动画元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32995776/