Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
javascript切换功能使页面滚动到顶部_Javascript_Html_Css - Fatal编程技术网

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

javascript切换功能使页面滚动到顶部,javascript,html,css,Javascript,Html,Css,我有一个小问题,在执行javascript函数后,网页返回到页面顶部 基本上,我有一个小的javascript函数,它通过改变div的显示样式来切换div的可见性。代码如下: <script type="text/javascript"> function toggle_visibility(id) { var e = document.getElementById(id); if(e.style.display == 'block')

我有一个小问题,在执行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';
    }

如果您能帮助解决此问题,我们将不胜感激
谢谢

建议不要使链接过载,而是使用范围:

使用


使用


单击事件后,您的链接将url重定向到“#”,因为您没有停止事件传播

您可以通过更改href
javascript:void(0)
来实现这一点


如果你问为什么。

在脚本标记中使用
是不推荐的。@reporter谢谢,我将删除itc)不要使用
href=“#”
javascript:void(null)工作得非常好:它什么都不做。然而,如果JS被禁用,
href=“#”
仍然会将您踢到页面顶部。-尝试一下-嗯,不,不是给我404!嗯,以前是这样的。不要介意。它很难看,右键单击会断开,在新选项卡中打开,如果您不喜欢,请使用spanI尝试上述操作,返回false只会使链接停止工作。此外,数字ID仅用作示例,它们通常具有良好的描述性名称。不过,我会将链接更改为spans,因为每个人似乎都认为这是一个更好的主意。谢谢你的帮助,这也意味着onclick不起作用,也意味着什么都不起作用。也没有js回退。我尝试了这个,它给了我一个“访问禁止403错误”@mplungjan我会将链接更改为一个span,因为你提到的原因。谢谢你的帮助:)请不要因为我而叹息:)
<a href="#" onclick="toggle_visibility('001');" class="expand">[+/-] Hide/Show Info</a> 
<div id="001" style="display:none;">
hello world
</div>
window.location = 'test.php#' + id; //where test.php is my current page
window.location.hash=id;
<style>
.expand { cursor:pointer; }
</style>

<span data-div="x001" 
 class="expand">[+/-] Hide/Show Info</a> 
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>
<a href="pleaseenablejs.html" data-div="x001" 
 class="expand">[+/-] Hide/Show Info</a> 
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> 
<a href="javascript:void(0)" onclick="toggle_visibility('001');" class="expand">[+/-] Hide/Show Info</a>