How to implement auto fixing a div like https://ww

2019-08-07 01:56发布

In Yahoo website, when scroll down, a blue part is fixed to the top, while if not scroll down, the blue part is not fixed.

How to implement this ?

May I try onScroll function?

4条回答
Melony?
2楼-- · 2019-08-07 02:19

Yes, you need to bind to win scroll like this:

var element = $(YOURTOPELEMENT)
    $(window).scroll(function () {
        var scrollTop = $(window).scrollTop();
        if (scrollTop > element.offset().top) {
            element.css({
                position: "fixed",
                top: 0
            })
        } else {
            element.css({
                position: "relative"
            })
        }
    })
查看更多
男人必须洒脱
3楼-- · 2019-08-07 02:20

I use inspect element and, apperantly it changes class when that "blue part" is not in view, so what it is doing (I guess) is changing the classes while it is in view and not in view, you can find if a div is in view and then change accordingly, "onscroll" is a great idea

查看更多
Root(大扎)
4楼-- · 2019-08-07 02:20

You can make it fixed just with css.

<div id="myHeader">Header stuff</div>

#myHeader {
  position: fixed;
  top: 0;
  width: 100%;
  z-index: 1000;
}
查看更多
等我变得足够好
5楼-- · 2019-08-07 02:23

Use $(window).scroll(function() on the part which you want to be fixed.

Fiddle Demo : Demo

$(window).scroll(function(){
    if ($(window).scrollTop() >= 100) {
       $('.sticky-header').addClass('fixed');
    }
    else {
       $('.sticky-header').removeClass('fixed');
    }
});

If you want to apply the fixed part to the header replace the class name in the $(window).scroll(function(){}): function.

Example for fixed Header while scrolling : Demo-2

查看更多
登录 后发表回答