jquery how to offset scroll position

2019-09-05 23:44发布

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?

标签: jquery scroll
3条回答
神经病院院长
2楼-- · 2019-09-06 00:17
$("#maincontent").scrollTop(300);
查看更多
太酷不给撩
3楼-- · 2019-09-06 00:25

Try

$('html, body').animate({
    scrollTop: $("#maincontent").offset().top - 100 // Means Less header height
},400);
查看更多
姐就是有狂的资本
4楼-- · 2019-09-06 00:30

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

$("#maincontent").offset().top - 100
查看更多
登录 后发表回答