[英]Javascript - Efficiency for scroll event, run code only once
这些if语句总让我晕眩。 如果页面带有标题,并且标记上方有隐藏标题。
<div id="headerfloat" style="display:none;">
<p>Floated header</p>
</div>
<div id="header">
<p>Header</p>
</div>
这个想法是,每当页面向下滚动超过225px时, #headerfloat
应该出现,并且当topScroll小于225px时消失。 我设法使用javascript和jQuery,但是当我在iPhone上测试它时,它非常缓慢。 而且我很确定这是因为代码是在每个滚动事件中运行的。 即使#headerfloat
可见,代码仍然会执行。 即使它没有那个时候。
所以,我需要确保代码只在需要时运行一次 。 我的第一个想法是添加和删除.open
和.closed
等类到#headerfloat
。 并在滚动事件期间运行if语句。 但这是最有效的方式吗?
我到目前为止,丑陋的片段:
jQuery(window).scroll(function () {
var headerfloat = $("#header_float");
var top = jQuery(window).scrollTop();
if (top > 225) // height of float header
{
if (!$(headerfloat).hasClass("closed")) {
$(headerfloat).addClass("boxshadow", "", 100, "easeInOutQuad").slideDown().addClass("open").removeClass("closed");
}
} else {
$(headerfloat).removeClass("boxshadow", "", 100, "easeInOutQuad").removeClass("closed").slideUp();
}
});
编辑:所以在laconbass的精彩回应之后,这是我最终得到的代码:
var mainHeader = $('#header')
, top_limit = mainHeader.outerHeight()
, $window = $(window)
;
var header_float = $('#header_float')
bindEvent();
function bindEvent() {
$window.scroll( scrollEvent );
}
function scrollEvent() {
var top = $window.scrollTop();
// avoid any logic if nothing must be done
if ( top < top_limit && !header_float.is(':visible')
|| top > top_limit && header_float.is(':visible')
) return;
// unbind the scroll event to avoid its execution
// until slide animation is complete
$window.unbind( 'scroll' );
// show/hide the header
if ( top > top_limit ) {
header_float.slideDown( 400, bindEvent );
} else {
header_float.slideUp( 400, bindEvent );
}
};
我假设如下:
fixed header
),您需要一个fixed
定位标题。 fixed headed
是页面主标题的克隆,类fixed
。 fixed header
。 fixed header
标题。 表现提示:
var mainHeader = $('header')
, header = mainHeader.clone().addClass('fixed').appendTo('body')
, top_limit = header.outerHeight()
;
bindEvents();
function bindEvents() {
$(window).scroll( scrollEvent );
}
function scrollEvent() {
var top = $(window).scrollTop();
// avoid any logic if nothing must be done
if ( top < top_limit && !header.is(':visible')
|| top > top_limit && header.is(':visible')
) return;
// unbind the scroll event to avoid its execution
// until slide animation is complete
$(window).unbind( 'scroll' );
// show/hide the header
if ( top > top_limit ) {
header.slideDown( 400, bindEvents );
} else {
header.slideUp( 400, bindEvents );
}
};
<header>
<h1>Awesome header</h1>
</header>
<div>
<!-- the page content -->
</div>
/* the real code needed */
header.fixed {
display: none;
position: fixed;
top: 0;
}
两种方式:
1,滚动时,如果已完成所需,请删除滚动事件。
2,var变量,默认为false,滚动,如果变量为false,你想要,并将变量设置为true ; 如果变量已经为真,则不执行任何操作(或其他您想要的操作)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.