防止默认 Firefox 在页面加载时滚动到锚标记



我有一个指向动态向div添加内容的页面的链接。我想要实现的是防止默认浏览器在页面加载时滚动到锚点。在搜索并尝试了在网络上找到的各种解决方案后,我最终得到了从这个堆栈溢出问题中复制的以下内容:

页1.html

<a href="url/to/page2/#anchor_name">link to page 2</a>

页2.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 上,窗口滚动到哈希中定义的元素,但当 id 属性再次添加到元素时,FF 滚动到该点(不包括标头高度(。任何想法为什么这不起作用?

只需将scroll-前缀添加到哈希中:

<a href="url/to/page2/#scroll-anchor-name">link to page 2</a>
<div id="anchor-name">...</div>

在运行时只需检查并删除它:

var hashtpl = "#scroll-";
if (hash && hash.match(RegExp('^' + hashtpl, 'gi')) !== null) {
hash = "#" + hash.substring(hashtpl.length());
...
}

最新更新