我正在尝试在视口中添加一个元素。我已经实现了这一点,但是当我滚动时,它会对我网站的性能造成严重问题。
我目前有这个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()
函数似乎在页面滚动时不断触发,我相信这可能是性能可能如此糟糕的原因。
在滚动不会导致我网站出现性能问题的网页时,是否有更有效的方法来添加类?
答案 0 :(得分:0)
每次$link=$_POST["link"];
事件被触发时,使用setTimeout
来延迟调用函数。在下面的代码中(我借用了from Codrops),设置了一个标志,在连续滚动的情况下每60毫秒调用一次该函数。
scroll
要使用它,请拨打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;
}
};
。
查看Codrops上的完整代码,了解new Scroller( document.getElementsByClassName('elements-to-watch') );
函数的实现。 Classie.js用于处理类名的分配。
如果您有什么不明白的话,请不要要求澄清!