鼠标经过显示层,鼠标移出后隐藏层,这种情况是非常常见的。假如有2个层:一个是内容层cont(默认显示),一个是提示层tip(默认隐藏)。当鼠标经过cont的时候tip显示,但当鼠标进入tip的时候(这时候鼠标已经移出cont),还要保证tip是显示。然后鼠标移出tip或移出cont(没有进入tip)的时候,tip层隐藏。
js代码
function tip(overClass, tipClass){
function getEvent(event){//获取事件对象
return event ? event : window.event;
}
function getRelatedTarget(event){//获取相关对象
if(event.relatedTarget){
return event.relatedTarget;
}else if(event.toElement){
return event.toElement;
}else if(event.fromElement){
return event.fromElement;
}else{
return null;
}
}
function getElementsByClass(searchClass,node,tag) {
var classElements = new Array();
if ( node == null )
node = document;
if ( tag == null )
tag = '*';
var els = node.getElementsByTagName(tag);
var elsLen = els.length;
var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
for (i = 0, j = 0; i < elsLen; i++) {
if ( pattern.test(els[i].className) ) {
classElements[j] = els[i];
j++;
}
}
return classElements;
}
var overArray = getElementsByClass(overClass),
tipArray = getElementsByClass(tipClass),
len = overArray.length;
for (var i = 0; i < len; i++){(function(i){
overArray[i].onmouseover = function(){//鼠标经过
tipArray[i].style.display = 'block';
}
overArray[i].onmouseout = function(event){//鼠标移出经过区
event = getEvent(event);
var relatedTarget = getRelatedTarget(event);
if (relatedTarget.className == tipClass){
tipArray[i].style.display = 'block';
}else{
tipArray[i].style.display = 'none';
}
}
tipArray[i].onmousemove = function(){//鼠标移动tip区
tipArray[i].style.display = 'block';
}
tipArray[i].onmouseout = function(){//鼠标移出tip区
tipArray[i].style.display = 'none';
}
})(i)
}
}
tip('hover', 'tip');
使用说明:函数tip的2个参数,
overClass:鼠标经过区(比如按钮)的样式类名;
tipClass:提示区样式类名。
html代码:
<div class="wrap">
<ul class="over_ul">
<li class="hover">第一个</li>
<li class="hover">第二个</li>
<li class="hover">第三个</li>
</ul>
<div class="tip" id="tip1"><div><div><a href="http://bianyuan.me" target="_blank">第一个提示内容</a></div></div></div>
<div class="tip" id="tip2"><span>第二个提示内容</span></div>
<div class="tip" id="tip3">第三个提示内容</div>
</div>
css代码:
div,ul,li{ margin:0; padding:0;}
.wrap{ position:relative; width:1002px; margin:0 auto; padding-top:20px;}
.over_ul{ overflow:hidden; list-style:none;}
.over_ul li{ float:left; width:100px; height:25px; line-height:25px; background-color:#CCC; border:1px solid #999; text-align:center;}
#tip1,#tip2,#tip3{ display:none; position:absolute; width:100px; height:60px; background-color:#060; font:bold 14px "宋体"; color:#fff; top:44px;}
#tip1{ left:0px;}
#tip2{ left:102px;}
#tip3{ left:204px;}