javascript - 防止默认 Firefox 在页面加载时滚动到锚标记
问题描述
我有一个指向动态添加内容到 div 的页面的链接。我想要实现的是防止默认浏览器在页面加载时滚动到锚点。在网络上搜索并尝试了各种解决方案后,我最终从这个堆栈溢出问题中复制了以下内容:
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 滚动到该点(不包括标题高度)。任何想法为什么这不起作用?
解决方案
只需将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());
...
}
推荐阅读
- python - 在 django 中删除外键时删除模型
- ios - 如何在 iOS 中测试键盘建议?
- google-apps-script - 部署时,Google App Script 清单文件被覆盖
- logging - 如何导出符合“在哪里查找日志”条件的日志?
- go - 如何使用 uber-go/zap 根据日志级别登录到标准输出或标准错误?
- gmail - 您可以过滤 gmail 以搜索特定数字的主题吗?
- c# - 将外部程序集加载到新的应用程序域并调用“基类”的方法
- javascript - 伪元素选择器下的属性“内容”被错误解析
- snowflake-cloud-data-platform - 从外部源加载到雪花需要哪个工具?
- flutter - Flutter Google Maps - 如何在自定义标记上添加动态文本