javascript - jQuery position DIV fixed on scroll - Stack Overflow

I tried to fixed an element on top, when this element touch the top of the window, when the user scroll

I tried to fixed an element on top, when this element touch the top of the window, when the user scroll down. On scroll down everything works (added a class with the fixed position), but when I scroll up doesn't work. but i don't understand why :( i created a jsfiddle with this code: /

$(window).scroll(function () {
     var distance = $('#navigation-sections').offset().top;

     if ($(window).scrollTop() >= $('#navigation-sections').offset().top) {
         $('#navigation-sections').addClass("affix");

     } else {
         $('#navigation-sections').removeClass("affix");
     }
 });

thanks

I tried to fixed an element on top, when this element touch the top of the window, when the user scroll down. On scroll down everything works (added a class with the fixed position), but when I scroll up doesn't work. but i don't understand why :( i created a jsfiddle with this code: http://jsfiddle/8h4knr9r/

$(window).scroll(function () {
     var distance = $('#navigation-sections').offset().top;

     if ($(window).scrollTop() >= $('#navigation-sections').offset().top) {
         $('#navigation-sections').addClass("affix");

     } else {
         $('#navigation-sections').removeClass("affix");
     }
 });

thanks

Share Improve this question asked Mar 4, 2015 at 0:49 mattiamattia 6212 gold badges9 silver badges24 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 5

You need to store the initial distance outside the scroll function - otherwise it will get recalculated every scroll. Here is the working fiddle: http://jsfiddle/donal/8h4knr9r/5/

The JS should look like this:

var distance = $('#navigation-sections').offset().top; 

$(window).scroll(function () {

     if ($(window).scrollTop() >= distance) {
         $('#navigation-sections').addClass("affix");

     } else {
         $('#navigation-sections').removeClass("affix");
     }
 });

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744272440a4566166.html

相关推荐

  • javascript - jQuery position DIV fixed on scroll - Stack Overflow

    I tried to fixed an element on top, when this element touch the top of the window, when the user scroll

    7天前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信