【问题标题】:javascript hashchange weird issue on forward buttonjavascript hashchange 转发按钮上的奇怪问题
【发布时间】:2012-05-29 11:28:10
【问题描述】:

当用户按下返回按钮时,我使用 onhashchange 事件自动滚动到 FAQ 页面中的锚链接。

它工作正常,除非按下前进按钮,滚动不起作用的情况。

我无法理解为什么会发生这种情况。有人知道为什么会这样吗?

演示页面:http://static.nemesisdesign.net/hashchange-issue/index.html(要重现该问题,请尝试单击左栏中的链接,然后按几次后退按钮,然后按前进按钮)

这是执行滚动的代码部分:

// if browser supports onhashchange event
if ("onhashchange" in window){
    $(window).bind('hashchange', function(e){
        e.preventDefault();
        var href = (location.hash != '') ? location.hash : '#container'
        scrollToFaq(href);
        return false;
    });
}

scrollToFaq = function(href){
    // scroll
    $('html, body').animate(
        // scroll to clicked item
        {scrollTop: $(href).offset().top},
        400, // duration in ms
        function(){
            if(href != '#container'){
                location.hash = href.replace('#',''); // update hash
            }
            // show back button if necessary
            if($(window).scrollTop() > 60){
                // onclick back to top button
                $('#back-top').fadeIn();
            }
        }
    );
}

// when clicking on a faq menu item
$('#faqmenu a').click(function(e){
    // prevent default behaviour
    e.preventDefault();
    // cache href attribute
    scrollToFaq($(this).attr('href'));
});

【问题讨论】:

  • 确实很奇怪。它似乎在事件触发之前跳跃。 here 也有人遇到类似问题。

标签: javascript jquery jquery-animate hashchange


【解决方案1】:

似乎在使用后退和前进按钮时,浏览器会执行其默认滚动操作,而不管onhashchange 事件处理程序中的e.preventDefault();

基本上这不会阻止浏览器在使用后退和前进按钮时跳转:

if ("onhashchange" in window){
    $(window).bind('hashchange', function(e){
        e.preventDefault();
        return false;
    });
}

我能想到的最简单的技巧是在哈希中使用一些不存在的 id(这样它就不会跳转)。

例如,对于引用 <div id="a">,您可以使用 <a href="#xxx_a">。然后你所要做的就是用javascript去掉xxx_部分。

但缺点是您破坏了禁用 javascript 的用户以及不支持 onhashchange 的浏览器的链接的默认行为。

您可以查看this jsFiddle 以查看工作示例

【讨论】:

    【解决方案2】:

    另一种方法是在文档准备好时使用 javascript 删除/更改 id 属性。这样你会很好地降级并绕过你在这里遇到的默认滚动行为......

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-11
      • 2014-08-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多