传入散列路径URL的窗口滚动 [英] Window scroll for incoming hash path url
问题描述
我有一个包含一些固定和绝对元素的页面,导致散列路径链接出现问题。我可以在用户使用 function(){window.scrollBy(0,-80)};
浏览页面时修复它,但是如果我尝试调用此函数在我的文档准备好(滚动传入散列)它不起作用。
I have a page with some fixed and absolute elements that are causing an issue for hash path links. I was able to fix it while the user is navigating around the page with function() { window.scrollBy(0, -80) };
however if I try to call this on my document ready (to scroll for incoming hashes) it does not work.
我发现它不起作用的原因是,在文档准备好之后,页面并没有实际调整到哈希。如果我无法做到这一点在文档准备好,我什么时候可以做到这一点?
I found the reason it does not work is that the page does not actually adjust to the hash until after the document ready. If I cannot do this at document ready when can I do it?
推荐答案
您可以尝试如下所示:
You could try something like this:
<script type="text/javascript">
$(function() {
// Retrieves the hash from URL
var hash = window.location.hash.substring(1);
// If hash length > 0 (there is actually a hash)
// And the #hash element exists on page
if(hash.length > 0 && $('#'+ hash).size() > 0){
// Binds a function to the page scroll
$(document).on('scroll', function(){
// Here's the bright part: when the browser finish loading the page, it will
// scroll right to the #hash element. So, whenever the page is scrolled, if
// the #hash element offset top matches the page scroll offset, it means the page
// was scrolled right to that element.
var elemTop = $('#'+ hash).offset().top; // Retrieve element's offset top
var docTop = $(document).scrollTop(); // Retrieve page's offset
if(elemTop == docTop){
alert('Now I do my stuff!! :)');
// Do your stuff
}
// And now you make sure "your stuff" won't happen again if the user
// accidentally scrolls precisely to the #hash element's offset by
// unbinding scroll action of the page.
$(document).unbind('scroll');
});
}
});
</script>
我希望能帮助您解决您的问题!让我知道是否有什么不清楚。
I hope that help you to solve your problem! Let me know if anything was unclear.
这篇关于传入散列路径URL的窗口滚动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!