js实现鼠标左右移动,图片也跟着移动效果
效果:鼠标往左移,图片对应右移,鼠标往右移,图片就左移动。图片距离越远偏移距离越大。
思路:首先获取图片原先的距离。设置一个变化值,图片的最终距离等于原先的距离加上变化值
布局:大盒子里面是图片,大盒子position:relative;图片position:absolute;
<!doctypehtml>
<html>
<head>
<metacharset="utf-8">
<title>无标题文档</title>
<style>
body{margin:0;}
#wrap{width:800px;height:500px;margin:30pxauto;border:1pxsolid#000;position:relative;}
#wrapimg{position:absolute;}
#wrapimg:nth-of-type(1){left:200px;top:200px;z-index:0;}
#wrapimg:nth-of-type(2){left:300px;top:180px;z-index:1;}
#wrapimg:nth-of-type(3){left:100px;top:100px;z-index:2;}
#wrapimg:nth-of-type(4){left:400px;top:110px;z-index:3;}
</style>
</head>
<body>
<divid="wrap">
<imgsrc="http://cdn.attach.qdfuns.com/notes/pics/201701/18/094455cpacwz1yai2ap43p.jpg.editor.jpg"/>
<imgsrc="http://cdn.attach.qdfuns.com/notes/pics/201701/18/094455csz3xxx1x23um7e9.jpg.editor.jpg"/>
<imgsrc="http://cdn.attach.qdfuns.com/notes/pics/201701/18/094455fv3rzfoov04owrof.jpg.editor.jpg"/>
<imgsrc="http://cdn.attach.qdfuns.com/notes/pics/201701/18/094455fv3rzfoov04owrof.jpg.editor.jpg"/>
</div>
<script>
varoWrap=document.getElementById("wrap");
varaImg=oWrap.getElementsByTagName("img");
variMax=4;
//获取图片的初始位置
for(vari=0;i<aImg.length;i++){
aImg[i].startX=parseInt(getStyle(aImg[i],'left'))
}
oWrap.onmousemove=function(ev){
ev=ev||window.event;
//获取鼠标的位置与大盒子中心点位置的距离
variX=ev.clientX-(oWrap.offsetLeft+this.offsetWidth/2)
for(vari=0;i<aImg.length;i++){
//获取每个img的z-index
variZindex=getStyle(aImg[i],'zIndex')
//Zindex越大移动的相对距离越小
variDisL=-parseInt(iX/iMax*(iMax-iZindex)/5)
//图片的距离等于原先的距离加上计算的距离
aImg[i].style.left=aImg[i].startX+iDisL+'px'
}
}
functiongetStyle(obj,attr)
{
if(obj.currentStyle){
returnobj.currentStyle[attr];
}
returngetComputedStyle(obj)[attr];
}
</script>
</body>
</html>
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持毛票票!