问题
When I add a HTML link to a specific part of the page:
<a href="#specific">test</a>
I noticed that it changes the URL at the address bar. Although I have come across websites where they link that way without the address bar being updated. How is this possible?
EDIT: It might be an AJAX solution were they make it work without URL change, as if I remember correctly, the page didn't reload, it went directly to the destination...
回答1:
You may wish to look at the jquery plugin, scrollTo.
http://jquery.com
And a couple of links for scrollTo
http://demos.flesler.com/jquery/scrollTo/
http://flesler.blogspot.com/2007/10/jqueryscrollto.html
You can do something like this:
The HTML
<a href="#scrollToMe" class="scrollLink">click me to scroll</a>
<div class="gap">a big gap</div>
<h1 id="scrollToMe">I should scroll to here without a # in the URL</h1>
The javascript (jquery and the scrollto plugin)
$(document).ready(function() {
$(".scrollLink").click(function(e) {
$.scrollTo($(this).attr("href"));
e.preventDefault();
});
});
What the javascript does, is when ever a link is clicked that has the class ".scrollLink", scroll the page down to the element that has the same ID, as the href for the particular link clicked. Then the e.preventDefault() stops it working like the normal hash link and stops it appearing in the URL bar.
Here is a working example for you: http://jsfiddle.net/alexkey/c3jsY/7/
And a version not in a frameset, so you can see that the URL doesn't change:
http://fiddle.jshell.net/alexkey/c3jsY/7/show/light/
This approach has a couple of good points
- Simply apply the scrollLink class to links you want to stop the hash appearing (nice and easy)
- It uses the normal href, which also means the links will still work even if javascript is disabled - good for accessibility and probably search engine optimisation to.
回答2:
It's possible to use javascript to intercept the click event, perform your own custom logic, then cancel the navigation event so the URL never changes
回答3:
Maybe you can try something like: window.scroll(0,150); instead of "(0,150)" put the cooridnate of your target.
回答4:
You'll have to experiment with the number (shown here as 200) to get the window to align properly.
<a href="javascript:void(0);" onclick="window.scroll(0,200);">test</a>
来源:https://stackoverflow.com/questions/8272215/how-do-i-add-a-html-hash-link-without-it-altering-the-url-bar