a标签下的img 为什么鼠标移入移出的事件同时触发啊

sinat_15207765 2015-11-02 10:19:31
部分代码如下:
<script type="text/javascript">

window.onload = function (){

var mDiv = document.getElementById('one'),
mA = mDiv.getElementsByTagName('a');
for (var i = 0; i < mA.length; i++) {
mA[i].onmouseover = function(){
console.log('1') }

};
for (var i = 0; i < mA.length; i++) {
mA[i].onmouseout = function(){
console.log('2')
}

};

}

</script>

问题是:鼠标移入每一个a标签时,会触发一次鼠标移入,一次鼠标移出,再一次鼠标移入,总共出发了三次事件,这是为什么啊!!
...全文
313 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
liusaint1992 2015-11-02
  • 打赏
  • 举报
回复
http://www.w3school.com.cn/tiy/t.asp?f=jquery_event_mouseenter_mouseover 另外,你可以考虑试试 这个事件 。

			for (var i = 0; i < mA.length; i++) {
				mA[i].onmouseenter = function(e){
						console.log('1') ;
				}

			};
			for (var i = 0; i < mA.length; i++) {
				mA[i].onmouseleave = function(e){
						console.log('2');
				}

			};
天际的海浪 2015-11-02
  • 打赏
  • 举报
回复
因为因为鼠标移入a标签下的img时也会触发a标签的 onmouseout 事件 你改用 jquery 的 mouseenter() 和 mouseleave() 就好了
liusaint1992 2015-11-02
  • 打赏
  • 举报
回复

		window.onload = function (){

			var mDiv = document.getElementById('one'),
			mA = mDiv.getElementsByTagName('a');
			for (var i = 0; i < mA.length; i++) {
				mA[i].onmouseover = function(e){
					if(checkHover(e,this)){ 
						console.log('1') ;
					}            
				}

			};
			for (var i = 0; i < mA.length; i++) {
				mA[i].onmouseout = function(e){
					if(checkHover(e,this)){ 
						console.log('2');
					}
				}

			};

		}

		function checkHover(e, target) {  
			if (getEvent(e).type == "mouseover") {  
				return !contains(target, getEvent(e).relatedTarget  
					|| getEvent(e).fromElement)  
				&& !((getEvent(e).relatedTarget || getEvent(e).fromElement) === target);  
			} else {  
				return !contains(target, getEvent(e).relatedTarget  
					|| getEvent(e).toElement)  
				&& !((getEvent(e).relatedTarget || getEvent(e).toElement) === target);  
			}  
		}  

		function contains(parentNode, childNode) {  
			if (parentNode.contains) {  
				return parentNode != childNode && parentNode.contains(childNode);  
			} else {  
				return !!(parentNode.compareDocumentPosition(childNode) & 16);  
			}  
		}  
//取得当前window对象的事件  
function getEvent(e) {  
	return e || window.event;  
}  

参考: http://blog.csdn.net/ltx851201/article/details/6800553 我这边试了可以解决,楼主试一试。
liusaint1992 2015-11-02
  • 打赏
  • 举报
回复
我错了,貌似不能,再看一下。
liusaint1992 2015-11-02
  • 打赏
  • 举报
回复
给a标签设置: width:图片width. height:图片height. 可以解决这个问题。

87,955

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 JavaScript
社区管理员
  • JavaScript
  • 无·法
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧