-->

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

2019-08-07 02:07发布

问题:

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?

回答1:

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



回答2:

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



回答3:

You can make it fixed just with css.

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

#myHeader {
  position: fixed;
  top: 0;
  width: 100%;
  z-index: 1000;
}


回答4:

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