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)
任何帮助将在修复此问题时受到赞赏谢谢.
建议不要使链接过载,而是使用跨度:
<style>
.expand { cursor:pointer; }
</style>
<span data-div="x001"
class="expand">[+/-] Hide/Show Info</a>
Run Code Online (Sandbox Code Playgroud)
我强烈建议
所以
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)
| 归档时间: |
|
| 查看次数: |
1941 次 |
| 最近记录: |