为所有哈希链接/调用的滚动位置添加自动偏移量 [英] Adding an automatic offset to the scroll position for all hash-links/calls

查看:97
本文介绍了为所有哈希链接/调用的滚动位置添加自动偏移量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下问题:

就像在Facebook上一样,我在页面顶部有一个始终可见的菜单栏(position: fixed;).现在,当我单击页面上的哈希链接(或加载带有url中的哈希值的新页面)以跳转到页面上的某个元素时,浏览器总是将此元素滚动到页面的顶部,这意味着元素位于顶部菜单栏的后面.

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.

我想添加一些Javascript(jQuery或普通Javascript),该Javascript自动向此滚动位置添加(负)偏移量,以便链接的元素位于顶部菜单栏的 下单击链接或加载页面时.但是我不只是想向所有处理此问题的链接添加事件侦听器.如果页面使用浏览器的地址栏在URL中加载了哈希部分(或链接到URL末尾带有哈希的其他页面时),我也想要一种有效的解决方案.

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

您可以在 http://loud.fm/tmp/details.html 上找到我页面的clickdummy.单击左侧图像右上角的评论气泡,以跳至评论.如果浏览器窗口足够小,则应在列出评论之前跳到灰色的"COMMENTS"标题和分页.我希望单击跳转链接后,标题和分页显示在顶部菜单的 下.

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! :)

关于, 雷内(René)

Regards, René

推荐答案

我实际上找到了一个对我有用的解决方案,仅使用css:

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

我在跳转链接指向的元素上添加了margin-top: -40px;padding-top: 40px;.这适用于所有主要浏览器:IE(7-9),Firefox,Opera,Chrome和Safari.

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!

这篇关于为所有哈希链接/调用的滚动位置添加自动偏移量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆