有没有办法重写浏览器的默认行为来点击散列? [英] Is there a way to override the browser's default behavior for clicking on hashes?

查看:167
本文介绍了有没有办法重写浏览器的默认行为来点击散列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我有以下情况时:

 < a name ='test'>< / a> 

...并在浏览器中加载它,我可以附加 #test 添加到URL,浏览器将滚动,以便< a> 位于页面顶部。

$ b $然而,我想改变这种行为(如果可能,使用JavaScript),以便使用散列不会滚动页面 - 如果没有删除< 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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆