我下面有以下代码,一旦元素scrollTop大于数字,它就会将div的位置更改为fixed。我正在尝试修改此脚本或找到其他解决方案,以便div在某个范围之间滚动并在某个点停止滚动(以便div不会离开页面或与页脚元素重叠。
我不知道是否正确的方法是说如果scrollTop大于150,然后position = fixed,如果大于600,则位置返回绝对值,或者是否有更好的方法,例如与底部的距离。 ..
而且我使用MooTools,而不是jQuery。我知道有一些jQuery选项/插件可以做到这一点。提前致谢!
window.onscroll = function()
{
if( window.XMLHttpRequest ) { // IE 6 doesnt implement position fixed nicely...
if (document.documentElement.scrollTop > 150) {
$('tabber').style.position = 'fixed';
$('tabber').style.top = '0';
} else {
$('tabber').style.position = 'absolute';
$('tabber').style.top = 'auto';
}
}
}
最佳答案
上面的脚本在许多级别上都是错误的。
不要使用window.onscroll
而是window.addEvent("scroll", function() {})
;
缓存选择器。在元素不更改的情况下,每次滚动使用$("tabber")
3次非常昂贵。
只需执行var tabber = $("tabber")
并引用它即可。
你不需要做
$("tabber").style.position = ...
$("tabber").style.top = ...
做:
tabber.setStyles({
position: "fixed",
top: 12123,
right: 24
});
有用于此的mootools插件,例如David Walsh的scrollSpy:http://davidwalsh.name/mootools-scrollspy
它可以让您在到达各种滚动目标或事件时设置脚本事件,请查看示例。
或者您也可以自己编写,例如,这花了我15分钟时间:
http://jsfiddle.net/dimitar/u9J2X/(手表http://jsfiddle.net/dimitar/u9J2X/show/)-到达页脚的20像素时,它不再固定。如果再次向上滚动,则返回固定状态。