开发者

Changing div postion depending on page scroll

I have the following code below that changes a div's position to fixed once an element scrollTop is greater than a number. I am trying to either amend this script or find a different solution so that the div will scroll between a range and STOP scrolling at some point ( so the div doesn't go off the page or overlap with footer elements.

I don't know if the right way is to say that IF scrollTop is greater than 150 then position=fixed, and if it's greater than 600 then position goes back to absolute, or if there's a better way, like distance from the bottom...

AND I use MooTools, not jQuery. I know there are a few jQuery options / plugins that do this. Thanks in advance!

window.onscroll = function()
{
    if( window.XMLHttpRequest ) { // IE 6 doesnt implement position fixed nicely...     
        if (docume开发者_开发技巧nt.documentElement.scrollTop > 150) {
            $('tabber').style.position = 'fixed';
            $('tabber').style.top = '0';

        } else {

            $('tabber').style.position = 'absolute'; 
            $('tabber').style.top = 'auto';


        }
    }
}


the script above is wrong on many levels.

don't use window.onscroll but window.addEvent("scroll", function() {});

cache selectors. using $("tabber") 3 times on each scroll when the element does not change is expensive.

just do var tabber = $("tabber") and reference that.

you don't need to do

$("tabber").style.position  = ... 
$("tabber").style.top  = ... 

do:

tabber.setStyles({
    position: "fixed",
    top: 12123,
    right: 24
});

There are mootools plugins for this, eg scrollSpy by David Walsh: http://davidwalsh.name/mootools-scrollspy

it can allow you to set scripted events upon reaching various scrolling destinations or events, look at the examples.

or you could just write it yourself, eg, this took me 15 mins to do: http://jsfiddle.net/dimitar/u9J2X/ (watch http://jsfiddle.net/dimitar/u9J2X/show/) - it stops being fixed when it reaches to 20 px of the footer. and then goes back to fixed if scrolling up again.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜