如何在哈希转换之前执行代码?(How do I execute code before a hashchange?)

编程入门 行业动态 更新时间:2024-10-24 02:02:18
如何在哈希转换之前执行代码?(How do I execute code before a hashchange?)

基本上,我想构建一个beforehashchange事件。 我想在hashchange事件影响页面之前执行代码(即:滚动到目标)。

我所知道的唯一可以改变哈希值(并导致hashchange事件)的事情是:

单击<a href="#foo"> ,在这种情况下,我可以捕获click事件,并检查指向哈希的链接。 手动更改URL栏中的哈希值,我可以忽略(除非有人知道在触发hashchange之前检测到这种情况的hashchange吗?)

还有其他方法可以触发hashchange吗?

Basically, I want to construct a beforehashchange event. I want to execute code before the hashchange event affects the page (i.e.: scrolls to the target).

The only things I know of that can change the hash (and cause a hashchange event) are:

clicking <a href="#foo">, in which case I could capture the click event, and check for a link to a hash. changing the hash in the URL bar manually, which I can probably ignore (unless someone knows a way to detect this before it triggers the hashchange?)

Are there other ways to trigger a hashchange?

最满意答案

只有hashchange事件。 要在哈希更改之前捕获一些信息,您可以向所有链接标记添加类似data-check-hash的属性:

<a href="#test" data-check-hash>foo</a>
 
$('body').on('click', 'a[data-check-hash]', function(e) {
    e.preventDefault();
    var $item = $(e.currentTarget), 
        hashValue = $item.attr('href').slice(1);

    // here goes your check code before hash change
    window.location.hash = hashValue;
    return false;
});

There is only hashchange event. To capture some information before hash change, you can add a attribute like data-check-hash to all link tags:

<a href="#test" data-check-hash>foo</a>
 
$('body').on('click', 'a[data-check-hash]', function(e) {
    e.preventDefault();
    var $item = $(e.currentTarget), 
        hashValue = $item.attr('href').slice(1);

    // here goes your check code before hash change
    window.location.hash = hashValue;
    return false;
});

                    
                     
          

更多推荐

本文发布于:2023-07-22 10:03:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1219190.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:代码   如何在   execute   code   hashchange

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!