jquery how to offset scroll position

2019-09-06 00:16发布

问题:

I have the following code that scrolls to a certain element:

$('html, body').animate({
         scrollTop: $("#maincontent").offset().top
     }, 400);

However, I have a fixed navbar at the top and so would like to be able to offset this. How can I offset it by a number of pixels?

回答1:

Try

$('html, body').animate({
    scrollTop: $("#maincontent").offset().top - 100 // Means Less header height
},400);


回答2:

$("#maincontent").scrollTop(300);


回答3:

$("#maincontent").offset().top just returns an integer, you only need to add or subtract to it to change the offset

$("#maincontent").offset().top - 100


标签: jquery scroll