我找不到一个确切的答案,试错也无济于事。
我正在生成一个动态PHP页面,在我的URL中有变量,所以我的URL看起来像:
http://www.mypage.com/myfile.php?l=1&d=1&c=1
(works)
我还想为此添加一个锚点,例如:
http://www.mypage.com/myfile.php?l=1&d=1&c=1#anchor1
(Does not jump to the anchor at the end)
锚点的目标是一个div,例如:
<a href = "http://www.mypage.com/myfile.php?l=1&d=1&c=1#anchor1">Some link</a>
<div id = "anchor1"></div>
这可能吗?
这应该能更好地工作
<a href="http://www.mypage.com/myfile.php?l=1&d=1&c=1#anchor1">Some link</a>
<div>
<a name="anchor1"></a>
</div>
请注意,正确的操作方式取决于您使用的doctype。您可以在此处阅读关于html5的更多信息,在此处阅读html 4.01的更多信息
我想问题在于id是动态添加的。
然后,您可以在添加id并将元素附加到文档后刷新哈希
var h = location.hash;
location.hash = '';
location.hash = h;
演示:http://jsfiddle.net/wpMDj/1/show/#anchor
代码:http://jsfiddle.net/wpMDj/1/
或者,您可以使用scrollIntoView
:
document.getElementById(location.hash.substring(1)).scrollIntoView(true);
但为了避免错误,你需要一些假设:
var hash = location.hash.substring(1);
if(hash){
var el = document.getElementById(hash);
if(el && el.scrollIntoView){
el.scrollIntoView(true);
}
}
演示:http://jsfiddle.net/wpMDj/3/show/#anchor
代码:http://jsfiddle.net/wpMDj/3/
某些浏览器不会根据URL哈希自动将id
作为目标。您可以考虑使用JavaScript。
var doc = document;
function E(e){
return doc.getElementById(e);
}
function offset(element){
var x = 0, y = 0, e = element;
while(e && !isNaN(e.offsetLeft) && !isNaN(e.offsetTop)){
x += e.offsetLeft - e.scrollLeft;
y += e.offsetTop - e.scrollTop;
e = e.offsetParent;
}
return {left: x, top: y};
}
function YourSolution(listId){
var parentId = E(listId), pcn = parentId.childNodes;
for(var i=0,l=pcn.length; i<l; i++){
if(pcn[i].nodeType === 1){
var ac = pcn[i].childNodes;
for(var n=0,m=ac.length; n<m; n++){
var an = ac[n];
if(an.nodeType === 1){
an.onclick = function(){
var el = offset(this);
scrollTo(el.left, el.top);
}
}
}
}
}
}
将以上内容放在一个名为scroll.js
的外部JavaScript页面上。现在将以下代码放在body
的底部:
<script type='text/javascript' src='scroll.js'></script>
<script type='text/javascript'>
YourSolution('listId');
</script>
</body>
</html>