我有一个经常会被问到的问题。问题是在任何地方都找不到明确的解决方案。
我有两个关于 anchor 的问题。
主要目标应该是在使用 anchor 跳转页面时获得一个漂亮干净的 url,其中没有任何哈希值。
所以 anchor 的结构是:
<ul>
<li><a href="#one">One</a></li>
<li><a href="#two">Two</a></li>
<li><a href="#three">Three</a></li>
</ul>
<div class="wrap">
<a name="one">text 1</a>
<a name="two">text 2</a>
<a name="three" class="box">text 3</a>
</div>
好的,如果您单击其中一个链接,该 url 将自动更改为
www.domain.com/page#1
最后这应该是:
www.domain.com/page
到目前为止,还不错。现在第二件事是,当您在互联网上搜索该问题时,您会找到 javascript
作为解决方案。
我找到了这个函数:
function jumpto(anchor){
window.location.href = "#"+anchor;
}
并调用该函数:
<a onclick="jumpto('one');">One</a>
什么会和以前一样。它将哈希添加到 url。我也加了
<a onclick="jumpto('one'); return false;">
没有成功。因此,如果有人可以告诉我如何解决这个问题,我将不胜感激。
非常感谢。
最佳答案
您可以获得目标元素的坐标并为其设置滚动位置。但这太复杂了。
这里有一个比较懒的方法:
function jump(h){
var url = location.href; //Save down the URL without hash.
location.href = "#"+h; //Go to the target element.
history.replaceState(null,null,url); //Don't like hashes. Changing it back.
}
这使用 replaceState
操纵网址。如果你也想要 support for IE , 那么你将不得不这样做 complicated way :
function jump(h){
var top = document.getElementById(h).offsetTop; //Getting Y of target element
window.scrollTo(0, top); //Go there directly or some transition
}
演示:http://jsfiddle.net/DerekL/rEpPA/
另一个带过渡:http://jsfiddle.net/DerekL/x3edvp4t/
您还可以使用 .scrollIntoView
:
document.getElementById(h).scrollIntoView(); //Even IE6 supports this
(我撒谎了。一点都不复杂。)
关于javascript - 使用javascript跳 anchor ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13735912/