Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
331 views
in Technique[技术] by (71.8m points)

javascript - jQuery position DIV fixed at top on scroll

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

});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...