Adding an automatic offset to the scroll position

2019-01-25 08:04发布

I have the following problem:

Like on Facebook, I have a menu bar at the top of the page that is always visible (position: fixed;). When I now click hash-links on my page (or load a new page with a hash in the url) to jump to a certain element on the page, the browser always scrolls this element to the very top of the page, meaning that the element is behind the top menu bar, afterwards.

I'd like to add some Javascript (jQuery or normal Javascript) that automatically adds a (negative) offset to this scroll position, so that the linked element is positioned right under the top menu bar when a link is clicked or the page is loaded. But I don't just want to add event listeners to all links that take care of this. I also want a solution that works, if the page is loaded with a hash portion in the url using the browser's address bar (or when linking to a different page with a hash at the end of the url).

You can find a clickdummy of my page at http://loud.fm/tmp/details.html. Click on the comments-bubble on the top right of the image on the left side to jump to the comments. If your browser window is small enough, you should jump to the grey "COMMENTS" headline and pagination right before the comments are listed. I'd want the headline and pagination to be displayed right under the top menu, after the jump link was clicked.

Can you help me with this, please? Thanks in advance! :)

Regards, René

8条回答
对你真心纯属浪费
2楼-- · 2019-01-25 08:32

I actually found a solution myself that worked for me, using only css:

I added a margin-top: -40px; and padding-top: 40px; to the element that the jump-link was pointing to. This works for all major browsers: IE (7-9), Firefox, Opera, Chrome and Safari.

Only problem: In case that this element is after a floated element, the negative margin doesn't work (meaning the positive padding becomes visible). Please comment, if anyone knows a solution/workaround for this. I'll update my post then. Thank you!

查看更多
我想做一个坏孩纸
3楼-- · 2019-01-25 08:32

Unfortunately (at least using Firefox) neither padding nor margin helps here (putting them on a 'main' div containing everything but the menubar); scrolling to an anchor always puts it at the very top of the page, fixed elements be damned.

I think you're going to have to go with your original idea, but remember that by using delegation you can set just one handler that will work with all the links in your menubar, including ones dynamically added.

查看更多
登录 后发表回答