【发布时间】:2020-01-31 17:04:49
【问题描述】:
我有一个指向动态添加内容到 div 的页面的链接。我想要实现的是防止默认浏览器在页面加载时滚动到锚点。在网上搜索并尝试了各种解决方案后,我最终从stack overflow question复制了以下内容:
page1.html
<a href="url/to/page2/#anchor_name">link to page 2</a>
page2.html
<div id="load-data-received-from-ajax"></div>
<script>
var hash = window.location.hash
var scrollToAnchor = function(hash) {
// If got a hash
if (hash) {
// Scroll to the top (prevention for Chrome)
window.scrollTo(0, 0);
// Anchor element
var term = $(hash);
// If element with hash id is defined
if (term) {
// Get top offset, including header height
var scrollto = term.offset().top - 55;
// Capture id value
var id = term.attr('id');
// Capture name value
var name = term.attr('name');
// Remove attributes for FF scroll prevention
term.removeAttr('id').removeAttr('name');
// Scroll to element
$('html, body, document').animate({scrollTop:scrollto}, 0);
// Returning id and name after .5sec for the next scroll
setTimeout(function() {
term.attr('id', id).attr('name', name);
}, 500);
}
}
};
$( document ).ready(function(){
$.ajax({
url: '',
type: 'get',
success: function(data){
$('#data').html(data);
scrollToAnchor(hash);
},
error: function (xhr, ajaxOptions, thrownError) {
$('#data').html('There was an error!);
}
});
});
</script>
这适用于 Chrome,但不适用于 Firefox。在 FF 上,窗口滚动到 hash 中定义的元素,但是当 id 属性再次添加到元素时,FF 滚动到该点(不包括标题高度)。任何想法为什么这不起作用?
【问题讨论】:
-
您可以将 url 中的哈希更改为与元素中找到的 id 不完全匹配。例如,在其上附加一些常量。虽然这可能不适用于所有情况,但您必须小心确保它不会在重新加载时中断。
-
@suddjian 我将 window.location.hash 存储在一个全局变量中(以便稍后使用它滚动到所需的点)并从 url 中完全删除哈希(我在 $ ( document ).ready(function(){}); FF 的行为仍然相同;只要将属性 id 添加到元素,它就会滚动到那里。
标签: javascript jquery firefox scroll anchor-scroll