What is the simplest jQuery way to have a 'position:fixed' (always at top) div?

后端 未结 6 574
醉梦人生
醉梦人生 2020-11-28 20:39

I\'m relatively new to jQuery, but so far what I\'ve seen I like. What I want is for a div (or any element) to be across the top of the page as if \"position: fixed\" worked

6条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-28 21:16

    Using this HTML:

    This stays at the top

    This is the javascript you want to use. It attaches an event to the window's scroll and moves the element down as far as you've scrolled.

    $(window).scroll(function() {
        $('#myElement').css('top', $(this).scrollTop() + "px");
    });
    

    As pointed out in the comments below, it's not recommended to attach events to the scroll event - as the user scrolls, it fires A LOT, and can cause performance issues. Consider using it with Ben Alman's debounce/throttle plugin to reduce overhead.

提交回复
热议问题