1. 程式人生 > >不浮誇且不單調——監聽鼠標圖片移動動畫

不浮誇且不單調——監聽鼠標圖片移動動畫

pla 500px -s weixin .cn z-index 移動圖片 att cte

鼠標監聽實現圖片動畫

  這是一個小的動畫,監聽鼠標的移動,來實現 圖片的移動視覺特效。雖然功能不是那麽的強大,但應用範圍還是很廣泛的,不浮誇且不是單調。

先給大家欣賞一下樣式。

小樣子

技術分享


代碼:
<!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軸的監聽移動。

技術分享 最後

    如果有更好的方式方法,期待大家分享,共同學習,共同進步。

不浮誇且不單調——監聽鼠標圖片移動動畫