Is there a way to override the browser's defau

2019-02-18 16:48发布

问题:

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.

回答1:

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)
  }
})


回答2:

Well, you can try to be brutal:

var i, elems = document.getElementsByTagName('a');
for (i = 0; i < elems.length; i++) {
    elems[i].removeAttribute('name');
}

It has to be run after the DOM is ready but before it gets rendered so you have to put it in the right place. It won't work for 'id' attributes - only with <a name=...>

Does it do what you want?



回答3:

Try this:

$( 'a[href="#"]' ).click( function(e) {
  e.preventDefault();
} );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>



回答4:

A kind-of hacky technique would be to just automatically scroll to the top of the page if there's a hash in the url:

if (window.location.hash) {
    window.scrollTo(0, 0);
}


回答5:

perhaps you need to use a bit of jquery and string manipulation

removeHashPartFromString = function() {
 ...
}

$('a').each(function() {
    this.attr('href') = removeHashPartFromString(this.attr('href'));
}); 

Or find the elements with the hash and remove the name hash attributes from those elements.