Swap CSS class on the basis of Scroll Position with Javascript

前端 未结 2 1898
天涯浪人
天涯浪人 2020-12-15 14:36

I\'m looking to re-create the Apple Store shopping cart sidebar.

http://store.apple.com/us/configure/MB535LL/A?mco=MTA4MTg3NTQ

It is similar to \"position:

2条回答
  •  萌比男神i
    2020-12-15 15:38

    You will have to handle the window.onscroll event, and check the element position, if the scrollTop is greater than the position of your element, you set the element fixed at top, if not, you place the element where it originally was.

    An example using jQuery:

    $(function () { 
      var $el = $('.fixedElement'), 
          originalTop = $el.offset().top;  // store original top position
    
      $(window).scroll(function(e){ 
        if ($(this).scrollTop() > originalTop ){ 
          $el.css({'position': 'fixed', 'top': '0px'}); 
        } else { 
          $el.css({'position': 'absolute', 'top': originalTop}); 
        } 
      }); 
    });
    

提交回复
热议问题