企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
## 定时器多态封装实现淡入淡出 > 效果如图: ![](https://box.kancloud.cn/cc3bc661929fe19d9933d96d765ee6e8_702x462.gif) >html代码 ``` <div id="parent"> <img src="images/landscape-test-1_1x.jpg" alt=""> <div id="fade"></div> </div> ``` >css代码 ``` #parent { width: 400px; height: 300px; padding: 20px; border: 1px solid black; margin-left: auto; margin-right: auto; position: relative; } #fade { background-color: #333; /* width: 400px; */ width: 100%; /* height: 300px; */ height: 100%; opacity: .1; position: absolute; top: 0; left: 0; } ``` >js代码 ``` var parent = document.getElementById("parent"); var fade = document.getElementById("fade"); var opacity = getComputedStyle(fade).opacity * 100; var timer; parent.onmouseover = function() { animate(70, 2); } parent.onmouseout = function() { animate(30, -2); } function animate(reach, add){ clearInterval(timer); timer = setInterval(function(){ if(opacity==reach){ clearInterval(timer); }else { opacity += add; console.log(opacity); fade.style.opacity = opacity / 100; } }, 50) } ```