让锚点链接到它的链接上方的一些像素 [英] Make anchor link go some pixels above where it's linked to
问题描述
我不确定要询问/搜索此问题的最佳方法:
当您点击锚链接时,它会将您带到页面,链接到的区域现在在页面的VERY TOP。我想锚点链接发送我到页面的那部分,但我想在顶部的一些空间。因为,我不想让它送到我的链接到部分与它在VERY TOP,我想要100像素的空间那里。
这有意义吗?这可能吗?
编辑以显示代码 - 只是一个锚标记:
< a href =#anchor>点击我!< / a>
< p id =anchor>我应该比我目前的位置低100px!< / p>
解决方案
addEventListener(hashchange,function(){
window.scrollTo(window.scrollX,window.scrollY - 100);
});
这将允许浏览器跳转到我们的锚点,然后我们将使用该位置偏移。
编辑:
正如@erb指出的,您在页面上,而哈希更改。在网址中输入
#something
的网页不适用于上述代码。这是另一个版本来处理://实际应用偏移的函数
function offsetAnchor b $ b if(location.hash.length!== 0){
window.scrollTo(window.scrollX,window.scrollY - 100);
}
}
//这将捕获页面上的哈希更改
window.addEventListener(hashchange,offsetAnchor);
//这里是这样,当你输入带有散列的页面时,
//它可以提供偏移量。有一个超时
//似乎需要允许浏览器首先跳转到锚点。
window.setTimeout(offsetAnchor,1); // 1的延迟是任意的,并且可能不总是正确的(虽然它在我的测试中)。
注意:
你可以在示例中用
$(window).on
替换window.addEventListener
感谢@Neon。I'm not sure the best way to ask/search for this question:
When you click on an anchor link, it brings you to that section of the page with the linked-to area now at the VERY TOP of the page. I would like the anchor link to send me to that part of the page, but I would like some space at the top. As in, I don't want it to send me to the linked-to part with it at the VERY TOP, I would like 100 or so pixels of space there.
Does this make sense? Is this possible?
Edited to show code - it's just an anchor tag:
<a href="#anchor">Click me!</a> <p id="anchor">I should be 100px below where I currently am!</p>
解决方案window.addEventListener("hashchange", function () { window.scrollTo(window.scrollX, window.scrollY - 100); });
This will allow the browser to do the work of jumping to the anchor for us and then we will use that position to offset from.
EDIT:
As was pointed out by @erb, this only works if you are on the page while the hash is changed. Entering the page with a
#something
already in the URL does not work with the above code. Here is another version to handle that:// The function actually applying the offset function offsetAnchor() { if(location.hash.length !== 0) { window.scrollTo(window.scrollX, window.scrollY - 100); } } // This will capture hash changes while on the page window.addEventListener("hashchange", offsetAnchor); // This is here so that when you enter the page with a hash, // it can provide the offset in that case too. Having a timeout // seems necessary to allow the browser to jump to the anchor first. window.setTimeout(offsetAnchor, 1); // The delay of 1 is arbitrary and may not always work right (although it did in my testing).
NOTE:
To use jQuery, you could just replace
window.addEventListener
with$(window).on
in the examples. Thanks @Neon.这篇关于让锚点链接到它的链接上方的一些像素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!