滚动时固定位置菜单,直到它到达相对容器的底部

Dan*_*Dan 2 javascript css jquery

我正在尝试用他们的Mo Map模拟Yelp的作用.

我知道如果元素到达某个屏幕滚动位置后如何将元素翻转到固定位置,但是一旦它到达相对容器的底部,你如何关闭固定位置?

该CSS粘位置解决了这一点,但因为它的相当新的,它不具有很大的覆盖面.

Chr*_*ris 7

你可以尝试做这样的事情:小链接.

这是JavaScript的注释版本:(注意:这使用jQuery,但没有必要.如果你需要一个简单的JavaScript版本,我很乐意提供一些提示)

var oritop = -100;
$(window).scroll(function() { //on scroll,
    var scrollt = window.scrollY; //get the amount of scrolling
    var elm = $(".box"); //get the box we want to make sticky
    if(oritop < 0) {
        oritop= elm.offset().top; //cache the original top offset
    }
    if(scrollt >= oritop) { //if you scrolled past it,
        elm.css({"position": "fixed", "top": 0, "left": 0}); //make it sticky
    }
    else { //otherwise
        elm.css("position", "static"); //reset it to default positioning
    }
});
Run Code Online (Sandbox Code Playgroud)

  • @Dan另外一个`if`就足够了:[little link](http://jsfiddle.net/glee/yLRVZ/4/). (2认同)