gpt4 book ai didi

javascript - 传入哈希路径 url 的窗口滚动

转载 作者:行者123 更新时间:2023-11-28 01:56:13 24 4
gpt4 key购买 nike

我有一个页面包含一些固定和绝对元素,这些元素导致哈希路径链接出现问题。当用户使用 function() { window.scrollBy(0, -80) }; 浏览页面时,我能够修复它但是如果我尝试在我的文档上调用它准备好(到滚动传入的哈希值)它不起作用。

我发现它不起作用的原因是在文档准备好之后页面才真正适应散列。如果我不能在文档准备好时执行此操作,我什么时候可以执行?

最佳答案

很明显浏览器只在整个页面加载后才从散列滚动到 HTML 元素 - 包括所有 JS - 我认为最好的选择是将操作绑定(bind)到 scroll 事件页。

你可以尝试这样的事情:

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

希望能帮到你解决问题!如果有任何不清楚的地方,请告诉我。

关于javascript - 传入哈希路径 url 的窗口滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16836720/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com