这些if语句总是让我头晕。如果有一个带有标题的页面,并且标记中在该页面上方有一个隐藏的标题。
<div id="headerfloat" style="display:none;">
<p>Floated header</p>
</div>
<div id="header">
<p>Header</p>
</div>
这个想法是,每当页面向下滚动超过 225 像素时,#headerfloat
就会出现,并在 topScroll 小于 225 像素时消失。我设法使用 javascript 和 jQuery 让它工作,但是当我在 iPhone 上测试它时,它非常缓慢。我很确定这是因为代码在每个滚动事件中运行。即使 #headerfloat
可见,代码仍然会执行。尽管此时还没有必要这样做。
因此,我需要确保代码仅在需要时运行一次。我的第一个想法是向 #headerfloat
添加和删除诸如 .open
和 .close
之类的类。并在滚动事件期间对这些语句运行 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 );
}
};
最佳答案
您开始的代码片段看起来有点难看。
I've made one on jsfiddle for your pleasure and reference
我假设如下:
- 当页面向下滚动时,您希望有一个
固定
定位的标题(也称为固定标题
)。 固定标题
是页面主标题的克隆,具有类fixed
。- 当页面向下滚动超过标题高度时,会显示
固定标题
。 固定标题
在页面向上滚动到足以显示主页标题时隐藏。
性能提示:
- 缓存 jQuery 对象以避免每次执行事件处理程序时都进行新查询。
- 在显示/隐藏动画之前取消绑定(bind)事件处理程序,然后重新绑定(bind)。
- 在事件处理程序上,尽快返回以避免不必要的逻辑。请记住,当执行 JavaScript 时,浏览器渲染进程会被阻止。
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;
}
关于Javascript - 滚动事件的效率,仅运行代码一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17187165/