首页 > 解决方案 > 防止默认 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 滚动到该点(不包括标题高度)。任何想法为什么这不起作用?

标签: javascriptjqueryfirefoxscrollanchor-scroll

解决方案


只需将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());
    ...
}

推荐阅读