javascipt中mouseout和mouseover事件冒泡介绍
来源:自学PHP网
时间:2014-09-19 14:47 作者:
阅读:次
[导读] 看到名字我们就知道mouseout和mouseover的用法,mouseout意思是移出窗口就执行mouseout的代码,而mouseover是经过是就执行mouseover中的程序。...
mouseover() 方法触发 mouseover 事件,或规定当发生 mouseover 事件时运行的函数
mouseout() 方法触发 mouseout 事件,或规定当发生 mouseout 事件时运行的函数。
先看一个实例
代码如下 |
复制代码 |
function showdiv()
{
$('J_CateList').style.display='block';
}
function hidediv()
{
$('J_CateList').style.display='none';
}
html
<div class="show-cate" id="J_ShowCate">
<span id="desc" onmouseover="showdiv();"></span>
<ul class="cate-list" id="J_CateList" onmouseout="hidediv();">
fdafdsafsa
</ul>
</div>
|
对于mouseout和mouseover事件冒泡的处理并不能像click事件一样通过evt.stopPropagation()和evt.cancelBubble=true来阻止事件冒泡
以下为一种解决方案:
代码如下 |
复制代码 |
function isMouseLeaveOrEnter(e, handler) {
if (e.type != 'mouseout' && e.type != 'mouseover') return false;
var reltg = e.relatedTarget ? e.relatedTarget : e.type == 'mouseout' ? e.toElement : e.fromElement;
while (reltg && reltg != handler)
reltg = reltg.parentNode;
return (reltg != handler);
}
使用:
element.onmouseout = function(e){
if(isMouseLeaveOrEnter(e, this)){
... // 操作函数
}
}
|
对函数的解释: 在标准浏览器中对于mouseover和mouseout可以通过e.relatedTarget获取触发事件的元素
在IE浏览器中mouseout的事件触发元素可以e.toElement获取,mouseover的事件触发元素可以通过e.fromElement获取
判断触发事件的元素是否是当前元素的子元素,如果是则不执行事件,也就解决了mouseout和mouseover的冒泡问题
JS阻止事件冒泡
代码如下 |
复制代码 |
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>js阻止事件冒泡的DEMO</title>
<script type="text/javascript">
//阻止冒泡的方法
function stopPP(e)
{
var evt = e || window.event;
//IE用cancelBubble=true来阻止而FF下需要用stopPropagation方法
evt.stopPropagation ? evt.stopPropagation() : (evt.cancelBubble=true);
}
</script>
</head>
<body>
<div style="margin: 150px 400px;width: 700px; height: 550px; background-color: #878788;" onclick="alert('最外层div上的onclick事件');">
<h2>最外层div上的onclick事件</h2>
<div style="margin: 100px; width: 500px; height: 300px; background-color: #545444;" onclick="stopPP(arguments[0]);alert('中间层div上的onclick事件');">
<h3>中间层div上的onclick事件</h3>
<div style="margin: 60px 100px; height: 100px; width: 300px; background-color: red;" onclick="stopPP(arguments[0]);alert('最内层div上的onclick事件');">
<h4>最内层div上的onclick事件”</h4>
</div>
</div>
</div>
</body>
</html> |
|