標籤:func line str 一個 ima lock play 特效 etc
滑鼠監聽實現圖片動畫
這是一個小的動畫,監聽滑鼠的移動,來實現 圖片的移動視覺特效。雖然功能不是那麼的強大,但應用範圍還是很廣泛的,不浮誇且不是單調。
先給大家欣賞一下樣式。
小樣子
代碼:
<!doctype html><html> <head> <meta charset="utf-8"> <title>滑鼠移動圖片</title> <style> body { margin: 0; background-image: url(img/beijing.jpg); } #wrap { width: 100%; height: 800px; margin: 30px auto; position: relative; } #wrap img { position: absolute; } #wrap img:nth-of-type(1){ width: 200px; height: 300px; left: 300px; top: 30px; z-index: 0; } #wrap img:nth-of-type(2){ width: 150px; height: 200px; left: 200px; top: 300px; z-index: 1; } #wrap img:nth-of-type(3){ width: 150px; height: 190px; right: 100px; top: 50px; z-index:2; } #wrap img:nth-of-type(4){ width: 200px; height: 200px; left: 400px; top: 30px; z-index: 3; } #wrap img:nth-of-type(5){ width: 200px; height: 200px; right: 500px; top: 70px; z-index: 4; } #wrap img:nth-of-type(6){ width: 200px; height: 200px; right: 200px; top: 200px; z-index: 5; } #wrap img:nth-of-type(7){ width: 400px; height: 400px; right: 35%; top: 200px; z-index: 6; } </style> </head> <body> <div id="wrap"> <img src="img/映像(2).png"/> <img src="img/映像(3).png"/> <img src="img/dada_man_ray_skulptur_cadeau_01.gif"/> <img src="img/映像(5).png"/> <img src="img/映像(6).png"/> <img src="img/capture_decran_2016_03_16_a_151542.jpg"/> <img src="img/映像(8).png"/> </div> <script> var oWrap = document.getElementById("wrap"); var aImg = oWrap.getElementsByTagName("img"); var iMax = 7; //擷取圖片的初始位置 for(var i = 0; i < aImg.length; i++) { aImg[i].startX = parseInt(getStyle(aImg[i], ‘left‘)) } oWrap.onmousemove = function(ev) { ev = ev || window.event; //擷取滑鼠的位置與div中心點位置的距離 var Yd = ev.clientX - (oWrap.offsetLeft + this.offsetWidth / 5) for(var i = 0; i < aImg.length; i++) { //擷取每個img的z-index var iZindex = getStyle(aImg[i], ‘zIndex‘) //Zindex越大移動的相對距離越小 var iDisL = -parseInt(Yd / iMax * (iMax - iZindex) / 20) //圖片的距離等於原先的距離加上計算的距離 aImg[i].style.left = aImg[i].startX + iDisL + ‘px‘ } } function getStyle(obj, attr) { if(obj.currentStyle) {
//IE瀏覽器 return obj.currentStyle[attr]; } return getComputedStyle(obj)[attr]; } </script> </body></html>
複製代碼後記得更改一片,我設定的是監聽#wrap範圍的滑鼠,只是監聽x軸的,大家可以研究添加y軸的監聽移動。
最後
如果有更好的方式方法,期待大家分享,共同學習,共同進步。
不浮誇且不單調——監聽滑鼠圖片移動動畫