<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>淡入淡出</title> <style type="text/css"> .div { width: 100px; height: 100px; background-color: red; margin-top: 50px; position: absolute; left: 100px; top: 0; cursor: pointer; opacity: 0.3; filter: alpha(opacity:30); } </style> <script type="text/javascript"> window.onload = function(){ var oDiv = document.getElementById('div'); oDiv.onmouseover = function(){ start(100); }; oDiv.onmouseout = function(){ start(30); } } var alpha = 30;//关键点 var timer =null; function start(iTarget){ var oDiv = document.getElementById('div'); clearInterval(timer); timer = setInterval(function (){ var speed = 0; if(alpha < iTarget){ speed = 10; }else{ speed = -10; }; if(alpha == iTarget){ clearInterval(timer) }else{ alpha+=speed;//关键点——忘了这一句。 oDiv.style.filter = 'alpha(opacity:'+alpha+')'; oDiv.style.opacity = alpha/100; } },30); } </script> </head> <body> <div class="div" id="div"></div> </body> </html>
学习路径:智能社的开发教程:https://ke.qq.com/webcourse/index.html#course_id=152997&term_id=100174752&taid=766913655494053&vid=v14127nxshc