如何在加载页面时禁用锚点"跳转"?

Ros*_*oss 101 jquery tabs href

我认为这可能是不可能的,我会尽力解释.我有一个包含选项卡(jquery powered)的页面,由以下内容控制:

我正在使用此代码,由前一个问题中的其他用户提供.

<script type="text/javascript">
    $(function() {

     $('html, body').animate({scrollTop:0}); // this is my "fix"

        var tabContent = $(".tab_content");
        var tabs = $("#menu li");
        var hash = window.location.hash;
     tabContent.not(hash).hide();
        if(hash=="") {
      $('#tab1').fadeIn();
     }
        tabs.find('[href=' + hash + ']').parent().addClass('active');

        tabs.click(function() {
            $(this).addClass('active').siblings().removeClass('active');
            tabContent.hide();
            var activeTab = $(this).find("a").attr("href");

            $(activeTab).fadeIn();
           return false;
        });

    });
</script>
Run Code Online (Sandbox Code Playgroud)

当我直接访问"标签页"时,此代码非常有用.

但是,我需要链接到其他页面的invidual标签 - 所以要做到这一点,代码获取window.location.hash然后显示适当的选项卡.

由于"返回false",页面不会"跳转"到锚点.

但是,此事件仅在单击事件时触发.因此,如果我从任何其他页面访问我的"标签",则会触发"跳转"效果.为了解决这个问题,我自动滚动到页面顶部,但我宁愿这不会发生.

是否有任何方法可以在页面加载时模拟"返回false",从而防止锚点"跳转".

希望这很清楚.

谢谢

dav*_*010 136

你的修复不起作用吗?我不确定我是否正确理解了这个问题 - 你有一个演示页吗?你可以尝试:

if (location.hash) {
  setTimeout(function() {

    window.scrollTo(0, 0);
  }, 1);
}
Run Code Online (Sandbox Code Playgroud)

编辑:经过测试,适用于Windows上的Firefox,IE和Chrome.
编辑2:移动setTimeout()内部if块,道具@vsync.

  • 我在没有`setTimeout`的空白页面上在Firefox中尝试过它并且它并不总是有效.你可能不需要它,如果它在jQuery的`$(function(){`无论如何.你真的不需要`location.hash`,但它很好留下它所以浏览器可能不需要做任何事情.提醒你scrollTo的用途! (3认同)
  • 英雄!是的,我的"修复"确实有效,但页面会"滚动"(正如我的代码告诉它的那样),我宁愿它也不会滚动.你的代码完美无缺.我没有看过ScrollTo - 功能是否必要?它似乎只用window.scrollTo(0,0)工作正常; (2认同)
  • 今天我遇到了同样的问题.我实际上必须将哈希(与选项卡名称/ href值相同)添加到我的导航链接.我最后在我的选项卡中添加了一个1-char后缀,然后在将它们与window.location.hash进行比较时将值字符串格式化为1个字符串(str.slice(0,-1).这样,哈希值不同,不会发生跳转. (2认同)
  • 这不会阻止浏览器跳转到主题标签,您必须放置一个空主题标签以防止“跳跃”,请在此处查看我的答案 http://stackoverflow.com/a/29823913/826194 (2认同)

Lar*_*zan 38

请参阅我的答案:Stackoverflow答案

诀窍是只删除主题标签ASAP并存储其值供您自己使用:

重要的是你不要把这部分代码放在$()或$(window).load()函数中,因为它会延迟并且浏览器已经移动到标记.

// store the hash (DON'T put this code inside the $() function, it has to be executed 
// right away before the browser can start scrolling!
var target = window.location.hash,
    target = target.replace('#', '');

// delete hash so the page won't scroll to it
window.location.hash = "";

// now whenever you are ready do whatever you want
// (in this case I use jQuery to scroll to the tag after the page has loaded)
$(window).on('load', function() {
    if (target) {
        $('html, body').animate({
            scrollTop: $("#" + target).offset().top
        }, 700, 'swing', function () {});
    }
});
Run Code Online (Sandbox Code Playgroud)


Spu*_*ley 12

还有其他方法可以跟踪您所使用的标签; 也许设置一个cookie,或隐藏字段中的值等等.

我会说,如果你不希望页面跳转加载,你最好使用其中一个选项而不是哈希,因为使用哈希优先于它们的主要原因是准确地允许你我想要阻止.

另一点 - 如果您的哈希链接与文档中的标记名称不匹配,页面将不会跳转,因此,如果您想继续使用哈希,您可以操纵内容以便标记的名称不同.如果您使用一致的前缀,您仍然可以使用Javascript在之间跳转.

希望有所帮助.

  • 好点.不要忘记在JS/CSS关闭时尝试保持页面可用/可访问. (2认同)

lop*_*ded 11

我使用了dave1010的解决方案,但是当我把它放在$().ready函数中时它有点跳跃.所以我这样做了:(不在$()内准备)

    if (location.hash) {               // do the test straight away
        window.scrollTo(0, 0);         // execute it straight away
        setTimeout(function() {
            window.scrollTo(0, 0);     // run it a bit later also for browser compatibility
        }, 1);
    }
Run Code Online (Sandbox Code Playgroud)


小智 10

  1. <element id="abc" />如果地址中有http://site.com/#abc哈希,则浏览器跳转到,并且可以看到id ="abc"的元素.所以,你应该默认隐藏元素:<element id="anchor" style="display: none" />.如果页面上没有id = hash的可见元素,则浏览器不会跳转.

  2. 创建一个脚本,检查url中的哈希值,然后查找并显示prrpopriate元素(默认情况下是隐藏的).

  3. 通过将onclick事件绑定到链接并指定return false;onclick事件的结果来禁用默认的"类似哈希的链接"行为.

当我实现制表符时,我写了类似的东西:

    <script>
    $(function () {         
        if (location.hash != "") {
            selectPersonalTab(location.hash);
        }
        else {
            selectPersonalTab("#cards");
        }
    });

    function selectPersonalTab(hash) {
        $("#personal li").removeClass("active");
        $("a[href$=" + hash + "]").closest("li").addClass("active");
        $("#personaldata > div").hide();
        location.hash = hash;
        $(hash).show();
    }

    $("#personal li a").click(function (e) {
        var t = e.target;
        if (t.href.indexOf("#") != -1) {
            var hash = t.href.substr(t.href.indexOf("#"));
            selectPersonalTab(hash);
            return false;
        }
    });
</script>
Run Code Online (Sandbox Code Playgroud)


kdm*_*try 8

没有一个答案对我来说不够好,我看到页面跳转到锚点,然后到顶部以获取某些解决方案,有些答案根本不起作用,可能多年来情况已经改变。希望我的功能会对某人有所帮助。

/**
 * Prevent automatic scrolling of page to anchor by browser after loading of page.
 * Do not call this function in $(...) or $(window).on('load', ...),
 * it should be called earlier, as soon as possible.
 */
function preventAnchorScroll() {
    var scrollToTop = function () {
        $(window).scrollTop(0);
    };
    if (window.location.hash) {
        // handler is executed at most once
        $(window).one('scroll', scrollToTop);
    }

    // make sure to release scroll 1 second after document readiness
    // to avoid negative UX
    $(function () {
        setTimeout(
            function () {
                $(window).off('scroll', scrollToTop);
            },
            1000
        );
    });
}
Run Code Online (Sandbox Code Playgroud)


小智 5

脏 CSS 只修复每次使用锚点时保持向上滚动(如果您仍然想使用锚点进行滚动跳转,则没有用,对于深层链接非常有用):

.elementsWithAnchorIds::before {
   content: "";
   display: block;
   height: 9999px;
   margin-top: -9999px; //higher thin page height
}
Run Code Online (Sandbox Code Playgroud)