How to hover a Fixed element until it reaches some point

后端 未结 9 2457
栀梦
栀梦 2021-02-07 11:54

I\'ve got a div which I need to be fixed to the bottom of the screen, until it reaches some point after scrolling and stop there and stay. If a user start scrolling back up - ma

9条回答
  •  不要未来只要你来
    2021-02-07 12:36

    I realize this is an old topic... however I needed to implement something of this nature recently. Below is the code to accomplish the task (keep in mind you may need to modify the css to get it to show in the appropriate location for your needs, mine was to dock the element at the top of the screen). Additionally, this is dependent on jQuery.

    $(document).ready(function () {
        //  initialize the dock
        Dock();
    
        // add the scroll event listener
        if (window.addEventListener) {
            window.addEventListener('scroll', handleScroll, false);
        } else {
            window.attachEvent('onscroll', handleScroll);
        }
    });
    
    function Dock() {
        Dock.GetDock = document.getElementById('dockable');
        Dock.NewScrollOffset = getScrollOffset();
        Dock.DockBottomPos = getDockBottomPos();
        Dock.DockTopPos = getDockTopPos();
    }
    
    function getScrollOffset() {
        var scrollOffset = window.pageYOffset
                    ? window.pageYOffset
                    : document.documentElement.scrollTop;
        return scrollOffset;
    }
    
    function getDockBottomPos() {
        var dockTopPos = getDockTopPos();
        var dockHeight = $('#dockable').height();
        return (dockTopPos + dockHeight);
    }
    
    function getDockTopPos() {
        var dockTopPos = $('#dockable').offset().top;
        return dockTopPos;
    }
    
    function handleScroll(){
         if (window.XMLHttpRequest) {
    
              //  determine the distance scrolled from top of the page
              Dock.NewScrollOffset = getScrollOffset();
    
              if (Dock.NewScrollOffset >= Dock.DockBottomPos) {
                  Dock.GetDock.className = "fixed";
                  return;
              }
              if (Dock.NewScrollOffset <= Dock.DockTopPos) {
                  Dock.GetDock.className = "";
              }
          }
     }
    

    css:

    #dockable
    {
        position: relative;
        width: inherit;
    }
    #dockable.fixed
    {
        position: fixed;
        top: 0px;
    }
    

    An example of a dock would be...

    #dockable div
    {
        display: inline;
        *zoom: 1;
        height: 25px;
        line-height: 25px;
        padding: 5px 10px 5px 10px;
    }
    
    

提交回复
热议问题