Home >Web Front-end >JS Tutorial >How to achieve continuous fade-in and fade-out in javascript

How to achieve continuous fade-in and fade-out in javascript

青灯夜游
青灯夜游Original
2021-10-18 15:48:492626browse

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.

How to achieve continuous fade-in and fade-out in javascript

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:

How to achieve continuous fade-in and fade-out in javascript

[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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn