【问题标题】:prevent default behaviour of a 'hashchange' event防止“hashchange”事件的默认行为
【发布时间】:2013-06-09 22:24:52
【问题描述】:

我正在使用 jQuery $(window).on('hashchange') 方法来隐藏不相关的部分,除了 URI-hash 指向的部分。它工作得很好,后退按钮和一切。除了我似乎无法阻止浏览器的默认行为之外,即向下滚动到匹配 id 的部分。

这是我的功能。

var AddHashNav = function (hashmatch, container) {
    $(window).on('hashchange', function (e) {
        if ( !window.location.hash ) {
            // empty hash, show only the default header
            change_preview(container, container + ' > header');
            return false;
        }
        // Don't do anything to hash links who's ids don't match
        else if ( window.location.hash.match(hashmatch) ) {
            change_preview(container, window.location.hash);
            return false;
        }
    });
}

var changePreview = function (container, preview) {
    $(container + ' >').addClass('hidden');
    $(preview).removeClass('hidden');
}

而调用者只是

$(document).ready(function () {
    // applay AddHashNav to all sections who's id ends in 'preview'
    AddHashNav(/preview?/, '.hash-nav-container');
});

e.preventDefault();return false; 我都试过了,但似乎都不起作用。

请注意,我试图阻止 hashChange 事件的行为,而不是 click 事件,here 这似乎是不可能的,但我确信至少有人已经设法弄清楚如何做到这一点。

【问题讨论】:

    标签: javascript jquery html preventdefault hashchange


    【解决方案1】:

    我通过在AddHashNav 构造函数的第一次调用上运行change_preview() 来修复它,因此隐藏了$(document).load() 调用上的部分。

    var AddHashNav = function (hashmatch, container) {
        // hide all sections except header on load
        change_preview()
        $(window).on('hashchange', function (e) {
            if ( !window.location.hash ) {
                // empty hash, show only the default header
                change_preview(container, container + ' > header');
                return false;
            }
            // Don't do anything to hash links who's ids don't match
            else if ( window.location.hash.match(hashmatch) ) {
                change_preview(container, window.location.hash);
                return false;
            }
        });
    }
    

    这不是最漂亮的解决方案。我不确定它为什么起作用(我认为这是因为这些部分在窗口对象中没有位置,因此无法滚动到),但它现在起作用了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-05-30
      • 1970-01-01
      • 2019-03-31
      • 2023-03-06
      • 2010-10-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多