Home >Web Front-end >JS Tutorial >How to achieve continuous fade-in and fade-out in javascript
Implementation method: 1. Use querySelector() to obtain the specified element object; 2. Use the "element object.style.opacity = Math.sin(2 * Math.PI * time)" statement to control the fade-in or fade-out Effect; 3. Use recursion to achieve continuous fade-in and fade-out.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
Javascript implements continuous fade in and out
You only need to find a periodic function with a scope of [0,1]. Use the value of the periodic function as the attribute value of opacity to control the fade-in or fade-out effect.
Use recursion to continue fading in and out.
Implementation code:
<h1 id="text">床前明月光,疑是地上霜。</h1> <script type="text/javascript"> var duration = 3000; var startTime = new Date(); var p = 0; requestAnimationFrame(function f(){ //获取到元素 var el = document.querySelector("#text"); var time = ( new Date - startTime ) / duration; el.style.opacity = Math.sin(2 * Math.PI * time); requestAnimationFrame(f); });
Rendering:
[Recommended learning: javascript advanced tutorial 】
The above is the detailed content of How to achieve continuous fade-in and fade-out in javascript. For more information, please follow other related articles on the PHP Chinese website!