Issue with DIV Show/Hide code?

天大地大妈咪最大 提交于 2019-12-20 03:05:17

问题


The below code allows a div to appear when the user rolls over a link. The issue is, is that the div doesn't disappear when the user rolls off the link. Is there anyway we can make it so that when the user rolls of the link the div disappears, but the user is still able to bring their cursor down and interact with items in the div..... any help would be appreciated.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
<script type='text/javascript'> 
 /* <![CDATA[ */ 
document.getElementsByClassName = function(){ 
    if(arguments.length == 1) 
    arguments[1]='*'; 
  var retnode = []; 
  var myclass = new RegExp('\\b'+arguments[0]+'\\b'); 
  var elem = this.getElementsByTagName(arguments[1]); 
  for(var i = 0; i < elem.length; i++){ 
    var classes = elem[i].className; 
    if(myclass.test(classes)) 
      retnode.push(elem[i]); 
  }; 
  return retnode; 
}; 
window.onload=function(){ 
  var x = document.getElementsByClassName('HoverMe', 'a'); 
  for(var i = 0; i < x.length; i++){ 
    x[i].onmouseover=function(){ 
      var m = document.getElementsByClassName('HoverMe', 'a'); 
      var n = document.getElementsByClassName('showMe', 'div'); 
      for(var i = 0; i<m.length; i++){ 
        n[i].style.display = (m[i]==this)?'block':'none'; 
      }; 
    }; 
  }; 
  x = document.getElementsByClassName('showMe','div'); 
  for(var i = 0; i < x.length; i++){ 
    x[i].style.display = 'none'; 
  }; 
}; 
/* ]]> */ 
</script> 

</head>

<body>
<a class='HoverMe'>link 1</a><a class='HoverMe'>link 2</a>
<div class='showMe'>stuff 1</div><div class='showMe'>stuff 2</div>
</body>
</html>

回答1:


Add a mouseout function. Add the following code under your x[i].mouseover function call:

x[i].onmouseout=function(){ 
  var m = document.getElementsByClassName('HoverMe', 'a'); 
  var n = document.getElementsByClassName('showMe', 'div'); 
  for(var i = 0; i<m.length; i++){ 
    n[i].style.display = 'none';
  }; 
};

Check out the fiddle here: http://jsfiddle.net/babcN/



来源:https://stackoverflow.com/questions/11916609/issue-with-div-show-hide-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!