js to achieve mouse left and right movement pictures also follow the movement effect

  • 2021-07-15 03:36:28
  • OfStack

Effect: When the mouse moves left, the picture moves right. When the mouse moves right, the picture moves left. The farther the picture distance, the greater the offset distance.

Idea: First, get the original distance of the picture. Set a change value, and the final distance of the picture is equal to the original distance plus the change value

Layout: There are pictures in the big box, and the big box position: relative;; Image position: absolute;;


<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title> Untitled document </title>
<style>
body{margin:0;}
#wrap{width:800px;height:500px;margin:30px auto; border:1px solid #000; position:relative;}
#wrap img{ position:absolute;}
#wrap img:nth-of-type(1){ left:200px;top:200px; z-index:0;}
#wrap img:nth-of-type(2){ left:300px;top:180px; z-index:1;}
#wrap img:nth-of-type(3){ left:100px;top:100px; z-index:2;}
#wrap img:nth-of-type(4){ left:400px;top:110px; z-index:3;}
</style>
</head>
<body>
<div id="wrap">
 <img src="http://cdn.attach.qdfuns.com/notes/pics/201701/18/094455cpacwz1yai2ap43p.jpg.editor.jpg" />
 <img src="http://cdn.attach.qdfuns.com/notes/pics/201701/18/094455csz3xxx1x23um7e9.jpg.editor.jpg" />
 <img src="http://cdn.attach.qdfuns.com/notes/pics/201701/18/094455fv3rzfoov04owrof.jpg.editor.jpg" />
 <img src="http://cdn.attach.qdfuns.com/notes/pics/201701/18/094455fv3rzfoov04owrof.jpg.editor.jpg" />
</div>
<script>
var oWrap=document.getElementById("wrap");
var aImg=oWrap.getElementsByTagName("img");
var iMax=4;
// Get the initial position of the picture 
for(var i=0;i<aImg.length;i++){
 aImg[i].startX=parseInt(getStyle(aImg[i],'left'))
}
oWrap.onmousemove=function(ev){
 ev=ev||window.event;
 // Gets the distance between the mouse position and the center point of the large box 
 var iX=ev.clientX-(oWrap.offsetLeft+this.offsetWidth/2)
 for(var i=0;i<aImg.length;i++){
 // Get each img Adj. z-index
 var iZindex=getStyle(aImg[i],'zIndex')
 //Zindex The larger the movement, the smaller the relative distance 
 var iDisL=-parseInt(iX/iMax*(iMax-iZindex)/5)
 // The distance of the picture is equal to the original distance plus the calculated distance 
 aImg[i].style.left=aImg[i].startX+iDisL+'px'
 }
}
function getStyle(obj,attr)
{
 if( obj.currentStyle){
 return obj.currentStyle[attr]; 
 }
 return getComputedStyle(obj)[attr]; 
}
</script>
</body>
</html>

Related articles: