有没有办法重写浏览器的默认行为来点击散列? [英] Is there a way to override the browser's default behavior for clicking on hashes?
问题描述
当我有以下情况时:
< a name ='test'>< / a>
...并在浏览器中加载它,我可以附加 #test
添加到URL,浏览器将滚动,以便< a>
位于页面顶部。
< a>的话,有没有办法做到这一点? 元素?
更新:我需要浏览器仍然发送 onhashchange()
事件,但不滚动到< a>
元素。原因是我想在保留事件通知的情况下重写滚动。
解决方案快速肮脏的黑客攻击可以建立在:
var curScroll = prevScroll = $(window).scrollTop()
$ (window).bind('scroll',function(){
prevScroll = curScroll
curScroll = $(this).scrollTop()
})。bind('hashchange',function( ){
$(this).scrollTop(prevScroll)
})
我在这里使用jQuery使它在各种浏览器中工作,并保持页面onhashchange和onscroll处理程序完好无损。我发现的一个问题是,如果你点击相同的话题标签两次,它会滚动。
UPD。我只是想出了一个更好的解决方案:
$ b $ $ p $ $'''''''''''''''''' {
if(this.href.split('#')[0] == location.href.split('#')[0]){
var scrollTop = $(window).scrollTop ()
setTimeout(function(){
$(window).scrollTop(scrollTop)
},0)
}
})
When I have the following:
<a name='test'></a>
...and load it in a browser, I can append #test
to the URL and the browser will scroll so that the <a>
is at the top of the page.
However, I would like to change this behavior (using JavaScript if possible) so that using the hash does not scroll the page - I'd like it to simply do nothing.
Is there a way to do that without removing the <a>
element?
Update: I need the browser to still send onhashchange()
events but without scrolling to the <a>
element. The reason being that I want to override the scrolling while retaining the event notification.
解决方案 A quick dirty hack, but it's something you can build upon:
var curScroll = prevScroll = $(window).scrollTop()
$(window).bind('scroll', function() {
prevScroll = curScroll
curScroll = $(this).scrollTop()
}).bind('hashchange', function() {
$(this).scrollTop(prevScroll)
})
I used jQuery here to make it work across browsers and keep the page's onhashchange and onscroll handlers intact. One problem I spotted is that if you click the same hashtag twice it scrolls anyway.
UPD. I just figured out a better solution:
$('a').live('click', function() {
if (this.href.split('#')[0] == location.href.split('#')[0]) {
var scrollTop = $(window).scrollTop()
setTimeout(function() {
$(window).scrollTop(scrollTop)
}, 0)
}
})
这篇关于有没有办法重写浏览器的默认行为来点击散列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!