以下是我的测试代码,需要用到jquery,主要是在火狐下发现了这一个问题
知识:
W3C在mouseover和mouseout事件中添加了relatedTarget属性。在mouseover事件中,它表示鼠标来自哪个元素,在mouseout事件中,它指向鼠标去往的那个元素。
而Microsoft添加了两个属性:
fromElement在mouseover事件中表示鼠标来自哪个元素。
toElement在mouseout事件中指向鼠标去往的那个元素。
<!DOCTYPE html>
<html>
<head>
<title>hover和mouseout</title>
<link rel="stylesheet" type="text/css" href="yy_jq_tools.css" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style type="text/css">
.warp{width:500px;margin:0 auto;margin-top:200px;}
.test{height:30px;width:100px;background:#f00;}
.test span{display:block;width:100px;height:30px;background:#0f0;}
</style>
</head>
<body>
<div class="warp" style="margin-top:100px;">
<div class="test"><span style="width:80%;"></span></div>
</div>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
var $test = $('div.test'),$span = $test.children('span');
var t_width = '100%',_cache;
$test.bind('mousemove',function(e){
var _this= $test,_x = e.clientX,_left = _this.offset().left,_w=_this.width();
var _wf = _x -_left;
if(_wf>0 && _wf<=_w){
_cache = Math.ceil(_wf*100/_w)+'%';
$span.css({width:_cache});
}
}).bind('mousedown',function(){
t_width = _cache;
$span.css({width:_cache});
});
$test.bind('mouseout',function(e){ // 火狐下有问题,出现不断的闪烁,一下子60%,一下子90%。
/* //这是jquery 1.0 中的代码 用于判断鼠标是否还在对象范围内
var p = (e.type == "mouseover" ? e.fromElement : e.toElement) || e.relatedTarget;
// Traverse up the tree
while ( p && p != this ) p = p.parentNode;
// If we actually just moused on to a sub-element, ignore it
if ( p == this ) return false;
*/
$span.css({width:t_width});
//relatedTarget W3C在mouseover和mouseout事件中添加了relatedTarget属性。在mouseover事件中,它表示鼠标来自哪个元素,在mouseout事件中,它指向鼠标去往的那个元素。
console.log(e.relatedTarget); // 发现有时候指向的是div.test 有时候指向的是span
});
/*
$test.hover(function(){},function(){//用了hover 火狐的问题解决了
$span.css({width:t_width});
});
*/
</script>
</body>
</html>
如果不使用jquery的那一段代码,发现div的颜色是一会儿绿,一会儿红,判断不正确。
查看jquery源码可发现hover是经过了对事件的处理来解决这个问题。