代碼:
<!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>