使用jQuery可以轻松使用fadeIn()和fadeOut()这两个动画方法。JavaScript的fadeIn和fadeOut实现代码又如何,看看下面的代码:
// fade out function fadeOut(el){ el.style.opacity = 1; (function fade() { if ((el.style.opacity -= .1) < 0) { el.style.display = "none"; } else { requestAnimationFrame(fade); } })(); } // fade in function fadeIn(el, display){ el.style.opacity = 0; el.style.display = display || "block"; (function fade() { var val = parseFloat(el.style.opacity); if (!((val += .1) > 1)) { el.style.opacity = val; requestAnimationFrame(fade); } })(); }
使用方法:
var el = document.querySelector('.js-fade'); fadeOut(el); fadeIn(el); fadeIn(el, "inline-block");
还可以使用CSS+JS方法:fadeOut
@keyframes fadeIn { to { opacity: 1; } } .fade-in { opacity: 0; animation: fadeIn .5s ease-in 1 forwards; } .is-paused { animation-play-state: paused; }
<div class='js-fade fade-in is-paused'>You look amazing!</div>
var el = document.querySelector('.js-fade'); if (el.classList.contains('is-paused')){ el.classList.remove('is-paused'); }