javascript切换功能会导致页面滚动到顶部

Iro*_*ash 4 html javascript css

在执行javascript函数后,网页返回到页面顶部时出现了一个小问题.

基本上,我有一个小的javascript函数,通过改变它的显示风格来切换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';
    }
Run Code Online (Sandbox Code Playgroud)

然后我用一个看起来像这样的链接调用它:

<a href="#" onclick="toggle_visibility('001');" class="expand">[+/-] Hide/Show Info</a> 
Run Code Online (Sandbox Code Playgroud)

div看起来像这样:

<div id="001" style="display:none;">
hello world
</div>
Run Code Online (Sandbox Code Playgroud)

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

我尝试在我的javascript函数结束时添加以下更改,但它们都不起作用:

window.location = 'test.php#' + id; //where test.php is my current page
Run Code Online (Sandbox Code Playgroud)

window.location.hash=id;
Run Code Online (Sandbox Code Playgroud)

任何帮助将在修复此问题时受到赞赏谢谢.

mpl*_*jan 8

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

现场演示

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

<span data-div="x001" 
 class="expand">[+/-] Hide/Show Info</a> 
Run Code Online (Sandbox Code Playgroud)

我强烈建议

  • 不使用数字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";
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

运用

<div id="x001">...</div>
Run Code Online (Sandbox Code Playgroud)

使用链接,您可以使用页面作为href告诉用户启用JS或遭受后果:)

<a href="pleaseenablejs.html" data-div="x001" 
 class="expand">[+/-] Hide/Show Info</a> 
Run Code Online (Sandbox Code Playgroud)

要解决你的代码,你需要返回false.在较新的浏览器中,使用event.preventDefault

function toggle_visibility(id) {
   var elm = document.getElementById(id);
   elm.style.display = elm.style.display == "block"?"none":"block";
   return false;
}
Run Code Online (Sandbox Code Playgroud)

运用

<a href="#" onclick="return toggle_visibility('001');" 
 class="expand">[+/-] Hide/Show Info</a> 
Run Code Online (Sandbox Code Playgroud)

  • c)不要使用`href ="#"` (2认同)