1. 程式人生 > 實用技巧 >JS 實現滑鼠移入移出透明度動畫變化效果

JS 實現滑鼠移入移出透明度動畫變化效果

程式碼:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        div {
            width: 300px;
            height: 300px;
            background-color
: #06c; opacity: 0.3 } </style> </head> <body> <div></div> <script> //當滑鼠移入div的時候 讓div的透明度 動畫變成1 滑鼠移出div 透明度動畫變回0.3 //1.獲取元素 var div = document.getElementsByTagName("div")[0]; var timer1 = null; var
timer2 = null; //2.給div 新增事件 div.onmouseover = function () { clearInterval(timer1); clearInterval(timer2); //透明度 ---> 1 //1.設定動畫三要素 var start = getStyle(div, "opacity") * 1; var end = 1; var step = 0.01;
//2.設定定時器 timer1 = setInterval(function () { //走一步的程式碼 //更新起點 start += step; if (start >= end) { clearInterval(timer1); start = end; } //設定樣式 div.style.opacity = start; }, 20) } div.onmouseout = function () { //透明度 --->0.3 clearInterval(timer1); clearInterval(timer2); //透明度 ---> 0.3 //1.設定動畫三要素 var start = getStyle(div, "opacity") * 1; var end = 0.3; var step = 0.01; //2.設定定時器 timer2 = setInterval(function () { //走一步的程式碼 //更新起點 start -= step; if (start <= end) { clearInterval(timer2); start = end; } //設定樣式 div.style.opacity = start; }, 20) } function getStyle(ele, prop) { //1.編寫主要程式碼 //如果 元素.currentStyle == undefined 標準瀏覽器中 if (ele.currentStyle == undefined) { //為了讓 別人 在函式外面 也能得到我們獲取的屬性值 我們要把屬性值返回出來 return getComputedStyle(ele)[prop]; } else { return ele.currentStyle[prop]; } //2.分析不確定的值 提取出來 作為引數 元素 屬性 //3.將引數帶入到 函式中 } </script> </body> </html>