我在这个问题上找不到可靠的答案,反复试验对我毫无帮助。
我用URL中的变量生成了一个动态PHP页面,所以我的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>这个是可能的吗?
发布于 2013-08-14 08:15:38
这应该能更好地工作
<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 here和html 4.01 here的更多信息
发布于 2013-08-14 08:05:50
某些浏览器不会根据id散列自动指向您的URL。您可以考虑使用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>发布于 2013-08-14 08:16:29
我猜问题在于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);但是为了避免错误,你需要一些if:
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/
https://stackoverflow.com/questions/18221144
复制相似问题