💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
[TOC] ## 1. 简单的fadeIn-fadeOut ![](https://box.kancloud.cn/ef94c2a54f13d2a8f0a38dd69505a494_656x440.gif) ~~~ <style> * { padding: 0; margin: 0; } img { width: 400px; } #parent { margin-left: auto; margin-right: auto; position: relative; width: 400px; border: 1px solid; padding: 20px; border-radius: 3px; } #fade { width: 100%; height: 100%; position: absolute; background: #2dae2d; opacity: 0.3; left: 0; top: 0; z-index: 10; } </style> ~~~ ~~~ <div id="parent"> <img src="images/01.png" alt=""> <div id="fade"></div> </div> <script> //使用定时器 /* 1.执行事件时先清除定时器 2.定时器中的内容,用if-else 来判断上下限 */ var parent = document.getElementById("parent"); var fade = document.getElementById("fade"); var timer; var opacity = getComputedStyle(fade).opacity * 100; parent.onmouseover = function () { clearTimeout(timer); timer = setInterval(function () { console.log(opacity + 2) if (opacity > 70) { clearTimeout(timer); } else { opacity += 2; fade.style.opacity = opacity / 100; } }, 50) } parent.onmouseout = function () { clearInterval(timer); timer = setInterval(function () { if (opacity < 30) { clearInterval(timer); } else { opacity -= 2; fade.style.opacity = opacity / 100; } }, 50) } </script> ~~~ ## 封装后的fadeIn-fadeOut ~~~ <script> //使用定时器 /* 1.执行事件时先清除定时器 2.定时器中的内容,用if-else */ var parent = document.getElementById("parent"); var fade = document.getElementById("fade"); var timer; var opacity = getComputedStyle(fade).opacity * 100; /* 1.进入事件后清除定时器 2.在定时器中,loop的代码和到达临界值清除定时器的代码,用if-else分割 */ 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; fade.style.opacity = opacity / 100; } }, 100) } </script> ~~~