Issue with DIV Show/Hide code?

2020-04-16 02:48发布

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条回答
甜甜的少女心
2楼-- · 2020-04-16 03:37

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/

查看更多
登录 后发表回答