Utilizing back and forward browser buttons for web apps
How do I use the back and forward browser buttons to navigate my javascript/jQuery web application? 开发者_如何转开发I know I can do window.location.href = 'this_url#placeholder'
and then perform the appropriate action. But when I do that, the browser scrolls to the element with that placeholder id (or to the top if there wasn't one). How do I get the browser to not scroll anywhere? I've seen this on other sites like facebook, what's the appropriate mechanism for this?
if you use location.hash
instead of location.href
the behaviour you specify shouldn't happen.
The HTML5 standard specifies new history features e.g. history.pushState()
which offer a nice replacement for this, but not all browsers support it yet.
If you don't want to roll your own framework, there are a number of javascript plugins which offer this functionality all packaged up nicely for easy use across browsers with slightly differing implementations. For example jquery history will use the newer history
options on browsers that support it and fall back to hash urls in browsers that don't.
I think this might answer your question:
add a hash with javascript to url without scrolling page?
Just use placeholders that are not actually defined in the page. If you have
<a name="contents">
Then use
<a href="#contentsarea">Contents</a>
To activate the contents section. The browser only scrolls if the hashtag has an anchor in the page.
You can add return false
after that or event.preventDefault
.
$("a#some_id").click(function(){
// do something cool
return false; // don't scroll to #some_id
});
See this thread for relevant discussion.
精彩评论