效果:鼠標往左移,圖片對應右移,鼠標往右移,圖片就左移動。圖片距離越遠偏移距離越大。
思路:首先獲取圖片原先的距離。設置一個變化值,圖片的最終距離等于原先的距離加上變化值
布局:大盒子里面是圖片,大盒子position:relative;圖片position:absolute;
<!doctype html><html><head><meta charset="utf-8"><title>無標題文檔</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;//獲取圖片的初始位置for(var i=0;i<aImg.length;i++){ aImg[i].startX=parseInt(getStyle(aImg[i],'left'))}oWrap.onmousemove=function(ev){ ev=ev||window.event; //獲取鼠標的位置與大盒子中心點位置的距離 var iX=ev.clientX-(oWrap.offsetLeft+this.offsetWidth/2) for(var i=0;i<aImg.length;i++){ //獲取每個img的z-index var iZindex=getStyle(aImg[i],'zIndex') //Zindex越大移動的相對距離越小 var iDisL=-parseInt(iX/iMax*(iMax-iZindex)/5) //圖片的距離等于原先的距離加上計算的距離 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>
以上就是本文的全部內(nèi)容,希望本文的內(nèi)容對大家的學習或者工作能帶來一定的幫助,同時也希望多多支持武林網(wǎng)!
新聞熱點
疑難解答