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

标签 javascript html 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';
    }

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

<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/

相关文章:

html - backface-visibility 不起作用并且透视()问题

html - 如何在 iframe 中定位 <img>?

javascript - 如何检测UA是否能够内嵌显示内容

javascript - 具有多个 child 的基准继承

javascript - 错误 : getaddrinfo ENOTFOUND when sending https request Node. js 和 API

javascript - 如何在MVC的 View 中添加时钟

javascript - 拉伸(stretch)一个 div 以填充空白

html - 内联跨度输入文本和按钮

javascript - 如何将行值移动到另一个表并重做 html 中的上一个表?

html - 居中滚动导航栏