如何在哈希转换之前执行代码?(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; });
更多推荐
发布评论