Home > Web Front-end > JS Tutorial > body text

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

青灯夜游
Release: 2021-10-18 15:48:49
Original
2605 people have browsed it

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);
});
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template