Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
214 views
in Technique[技术] by (71.8m points)

javascript - Adding an automatic offset to the scroll position for all hash-links/calls

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).

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...