jQuery position DIV fixed at top on scroll

℡╲_俬逩灬. 提交于 2019-11-26 09:52:00

问题


I have a page that\'s fairly long and within the layout\'s menu, there\'s a flyout menu. I\'d like this flyout portion of the menu to show at the top of the page even when the user has scrolled the menu bar out of view. Here\'s the HTML for the menu

<div id=\"task_flyout\">
        <div id=\"info\">Compare up to 3 cards side-by-side. Click “Add to Compare” next to any card to get started…</div>
        <div id=\"card1\" class=\"card\">
            <div class=\"cardimage\"></div><div class=\"cardname\"><a href=\"#\"></a></div><div class=\"remove\"><a href=\"#\"><img src=\"images/remove.png\" alt=\"remove card\" width=\"12\" height=\"12\" border=\"0\" /></a></div>
        </div>
        <div id=\"card2\" class=\"card\">
            <div class=\"cardimage\"></div><div class=\"cardname\"><a href=\"#\"></a></div><div class=\"remove\"><a href=\"#\"><img src=\"images/remove.png\" alt=\"remove card\" width=\"12\" height=\"12\" border=\"0\" /></a></div>
        </div>
        <div id=\"card3\" class=\"card\">
            <div class=\"cardimage\"></div><div class=\"cardname\"><a href=\"#\"></a></div><div class=\"remove\"><a href=\"#\"><img src=\"images/remove.png\" alt=\"remove card\" width=\"12\" height=\"12\" border=\"0\" /></a></div>
        </div>
        <div id=\"compare\"><a href=\"comparecards.php\">Compare Now</a></div>
    </div>
    <div id=\"task_arrow\"></div>
</div>

And here\'s the script. I\'m locking the nav bar \".frozen_top\" to the top of the browser window on scroll (that\'s working correctly so far), but additionally, I\'d like to change the CSS positioning on \"#task_flyout\" once that bar locks.

$(window).scroll(function(){
if($(document).width() > 900) { 
    $(\".frozen_top\").css(\"top\",Math.max(130,$(this).scrollTop()));
    if($(this).scrollTop() > 135) {
        $(\".frozen_top\").css(\"margin-top\",\"-95px\");
                    $(\"#task_flyout\").css(\"top\",\"53px\");    
    } else {
        $(\".frozen_top\").css(\"margin-top\",\"-5px\");
                    $(\"#task_flyout\").css(\"top\",\"33px\");    
    }
}

});

回答1:


instead of doing it like that, why not just make the flyout position:fixed, top:0; left:0; once your window has scrolled pass a certain height:

jQuery

  $(window).scroll(function(){
      if ($(this).scrollTop() > 135) {
          $('#task_flyout').addClass('fixed');
      } else {
          $('#task_flyout').removeClass('fixed');
      }
  });

css

.fixed {position:fixed; top:0; left:0;}

Example



来源:https://stackoverflow.com/questions/20100461/jquery-position-div-fixed-at-top-on-scroll

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!