关于鼠标移动事件晃动问题解决方案

做网页特效经常用到onmousemove事件,多见于显示当前目标的某些信息,但是经常会出现弹出框晃动的情况,原因基本都是鼠标脱离了当前元素跑到其他元素上了直接导致弹出层消失,这个过程不断重复就出现了晃动的情况,下面是本人写的一些代码示例,就出现了晃动的情况(例子中的图片随便找,小图尺寸170*170,大图尺寸400*400)

HTML:

<div id="target">
	<ul class="clearfix">
		<li><img src="images/shirt_1.jpg" alt=""></li>
		<li><img src="images/shirt_2.jpg" alt=""></li>
		<li><img src="images/shirt_3.jpg" alt=""></li>
		<li><img src="images/shirt_4.jpg" alt=""></li>
	</ul>
	<div id="box"></div>
</div>    

CSS:

body,div,p,ul,li,img{margin:0;padding:0; background: #233; list-style: none;}
#target{ padding: 10px; background: white;  }
#target ul li{ width: 170px; height: 170px; border:1px solid gray; float: left; margin: 10px; }
#target #box{width: 400px; height: 400px; border:1px solid gray; position: absolute; display: none; background: url(images/loading.gif) center center no-repeat white;}

JavaScript:

var target = document.getElementById('target');
var imgList = target.getElementsByTagName('li');
var oBox = document.getElementById("box");
var len = imgList.length;
for(var i=0;i<len;i++){
	imgList[i].onmouseover = function(event){
		event = event || window.event;
		target = event.target || event.srcElement;
		oBox.style.display = "block";
		var oImg = document.createElement("img");
		var img = new Image();
		img.src = oImg.src = String(this.getElementsByTagName("img")[0].src).replace(/\.(jpg)$/g,"_big.jpg");//这里也要注意一下
		img.complete ? oBox.appendChild(img) : function(){
			oImg.onload = function(){
				oBox.appendChild(oImg)
			}
		}
	}
	imgList[i].onmousemove = function(event){
		event = event || window.event;
		oBox.style.left = (event.clientX + 20) + "px"; //注意这里的+20
		oBox.style.top = (event.clientY + 20) + "px"; //注意这里的+20
	}
	imgList[i].onmouseout = function(event){
		event = event || window.event;
		oBox.style.display = "none";
		oBox.innerHTML = "";
	}
}

如果把代码中的+20去掉,就会出现晃动的情况

另外还有个问题要注意一下:

img.src = oImg.src = String(this.getElementsByTagName("img")[0].src).replace(/\.(jpg)$/g,"_big.jpg");

如果把代码换成这样就会出问题

img.src = oImg.src = String(target.src).replace(/\.(jpg)$/g,"_big.jpg");

鼠标移动时出现了404,问题还在于target值,当鼠标移动到两个图片中间时就会出现这样的情况,原因是鼠标在两幅图中间时target值是li而不是图片,因此就获取不到src的值,改成this.getElementsByTagName("img")[0].src就可以了

 

posted @ 2016-03-08 12:24  点点乐淘淘  阅读(1593)  评论(0编辑  收藏  举报