简体   繁体   中英

How to add a class to an html element when a web page has been scrolled several px

I want to add a class to $ ('# header') when my web page scrolls down by 100px
this is the code:

$(window).scroll(function(){
var offset = $(window).offset();
if (offset.top > 100) {
    $('#header').addClass('header2')
}
else {
    $('#header').removeClass('header2')
};
});

#JQueryCode

Please use below mention code

 $(window).scroll(function() { var scroll = $(window).scrollTop(); //console.log(scroll); if (scroll >= 50) { //console.log('a'); $("#header").addClass("header2"); } else { //console.log('a'); $("#header").removeClass("header2"); } });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM