开发者

Javascript help, toggle text keeps jumping back to top of page

I hope someone can help with this issue, I've tried many scripts开发者_如何学运维 and workarounds, but can't get this simple thing to work. As the title has it, how can I make my text NOT jump to the top of the page. Here is the code:

<script type="text/javascript">
function toggleVisibility() {
  document.getElementById("toggleMe").style.display = "";
  if(document.getElementById("toggleMe").style.visibility == "hidden" ) {
    document.getElementById("toggleMe").style.visibility = "visible";
  }
  else {
  document.getElementById("toggleMe").style.visibility = "hidden";
   ev.preventDefault();
    return false;

  }
}
</script>



 <a href="#" onclick="toggleVisibility();">Click to toggle visibility.</a></p>
 
<div id="toggleMe" style="visibility: hidden;"> Something to Hide and show.

Display collapses it's layout while visibility will keep it's layout.

All in the same html file. I read what outhers did and I tried the

ev.preventDefault(); return false;

code at the end of the function, but nothing.


Change the href attribute in the A tag to: javascript:; instead of #

So use this to create your javascript enabled anchor:

<a href="javascript:;">

added (background info):

The # character indicates a bookmark. By omitting the name of the bookmark e.g. #bottom the browser considers the bookmark as 'top of the page' thus scrolling to the top. Your problem does not have to do anything with bookmarks, however using # to define an empty link for a javascript enabling anchor (A) tags is not the way to go. You should use: javascript:; or javascript:void(0); to indicate that this is not a navigation anchor.


Or simply always return false, not just in the Else clause.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜