我有一个小问题,在执行 javascript 函数后,网页返回到页面顶部。

基本上,我有一个小的 javascript 函数,它通过更改 div 的显示样式来切换 div 的可见性。代码如下:

<script type="text/javascript">
    function toggle_visibility(id) {
       var e = document.getElementById(id);
       if(e.style.display == 'block')
          e.style.display = 'none';
       else
          e.style.display = 'block';
    }

然后我用一个看起来像这样的链接来调用它:
<a href="#" onclick="toggle_visibility('001');" class="expand">[+/-] Hide/Show Info</a>

div 看起来像这样:
<div id="001" style="display:none;">
hello world
</div>

这工作得很好。但是当我点击我的“展开/隐藏”链接来切换 div 的可见性时,页面总是返回顶部,所以我每次都必须向下滚动到底部。

我尝试在我的 javascript 函数末尾添加以下更改,但它们都不起作用:
window.location = 'test.php#' + id; //where test.php is my current page


window.location.hash=id;

解决此问题的任何帮助将不胜感激
谢谢。

最佳答案

建议不要重载链接,而是使用跨度:

Live Demo

<style>
.expand { cursor:pointer; }
</style>

<span data-div="x001"
 class="expand">[+/-] Hide/Show Info</a>

我也强烈建议
  • 不使用数字 ID
  • 不使用内联事件处理程序

  • 所以
    window.onload=function() {
      var links = document.querySelectorAll(".expand");
      for (var i=0;i<links.length;i++) {
        links[i].onclick=function(e) {
          e.preventDefault();
          var ele = document.getElementById(this.getAttribute("data-div"));
          if (ele) ele.style.display = ele.style.display == "block"?"none":"block";
        }
      }
    }
    

    使用
    <div id="x001">...</div>
    

    通过链接,您可以使用页面作为 href 告诉用户启用 JS 或承担后果:)
    <a href="pleaseenablejs.html" data-div="x001"
     class="expand">[+/-] Hide/Show Info</a>
    

    要修复 您的 代码,您需要返回 false。在较新的浏览器中,使用 event.preventDefault
    function toggle_visibility(id) {
       var elm = document.getElementById(id);
       elm.style.display = elm.style.display == "block"?"none":"block";
       return false;
    }
    

    使用
    <a href="#" onclick="return toggle_visibility('001');"
     class="expand">[+/-] Hide/Show Info</a>
    

    关于javascript切换功能使页面滚动到顶部,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25183986/

    10-12 00:14
    查看更多