How to implement auto fixing a div like https://www.yahoo.com

眉间皱痕 提交于 2019-12-11 06:04:39

问题


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


来源:https://stackoverflow.com/questions/23487573/how-to-implement-auto-fixing-a-div-like-https-www-yahoo-com

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!