【发布时间】:2012-10-05 00:07:57
【问题描述】:
下面是一个模拟iOS设备上看到的sticky header效果的小脚本。
$('.scrolllist').scroll(function(){
$(this).find('ul').each(function(){
if($(this).position().top <= 0){
$(this).addClass('abs').find('strong').removeClass('mov');
if($(this).position().top <= ($(this).height() * -1)){
$(this).removeClass('abs');
$(this).find('strong').addClass('mov');
}
else {
$(this).addClass('abs');
$(this).find('strong').removeClass('mov');
}
}
else {
$(this).removeClass('abs').find('strong').removeClass('mov');
}
});
});
它通过将每个元素的状态从postion:absolute, top:0 更改为position:absolute, bottom:0; 来更改每个元素的位置,同时还将包含的<ul> 从position:relative 更改为position:static
示例:http://jsfiddle.net/dMJqj/80/
有什么办法可以让它变得更平滑一点。它在 Chrome 和 Firefox 上看起来有点生涩,有时可能需要几分之一秒才能触发,这很明显,因为粘性标题似乎闪烁。
【问题讨论】:
-
在 FF 和 Chrome 中对我来说看起来很流畅。
strongs与滚动条重叠会让我更加恼火。 -
这里的一个潜在问题是您的代码无效。
ul只能将lielements 作为其直接子级。因此,您需要将strong标签包装在li中,或者将它们移到ul之外。 -
@Christoph 这也很烦人。你知道如何阻止它这样做吗?
-
正如 Christoph 已经提到的,您的 HTML 无效。您可以使用普通的
<li>Elements 和使用:first-child选择器轻松避免购买。另外,请查看 John Resig 的以下文章,其中他解释了如何处理滚动事件:ejohn.org/blog/learning-from-twitter
标签: jquery scroll position absolute