jQuery位置DIV固定在滚动的顶部

jQuery position DIV fixed at top on scroll

本文关键字:滚动 顶部 位置 DIV jQuery      更新时间:2023-09-26

我有一个相当长的页面,在布局的菜单中,有一个弹出菜单。我希望菜单的弹出部分显示在页面顶部,即使用户已经将菜单栏滚动到视图之外。这是菜单的HTML

<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>

这是剧本。我正在滚动时将导航栏".frozen_top"锁定在浏览器窗口的顶部(到目前为止工作正常),但另外,一旦该栏锁定,我想更改"#task_flyout"上的CSS位置。

$(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");    
    }
}
});

与其这样做,为什么不在窗口滚动经过一定高度后使弹出按钮position:fixed, top:0; left:0;

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;}

示例