search
HomeWeb Front-endJS TutorialHow to achieve fade-in and fade-out effect in js_javascript skills

The fade in and fade out effect is often used in daily projects. Unfortunately, native JS does not have a similar method, and sometimes small pages are not worth introducing a jQuery library, so I wrote one myself. It has been encapsulated and is useful. Friends, you can use it directly. There is also a method for setting element transparency in the code. It is set according to IE rules (0~100). If it is changed to the standard setting method (0.00~1.00), please consider floating point to accurately express the difference when using it below.

Parameter description:
Both fadeIn() and fadeOut() have three parameters. The first one is event, which is required; the second one is fade speed, which is a positive integer. You can weigh the size by yourself. It is optional. Parameter; the third one is to specify the transparency value to fade in and out to (similar to fadeTo() in jQuery), a positive integer value from 0 to 100, which is also an optional parameter.
Key code:

 //淡入效果(含淡入到指定透明度) 
 function fadeIn(elem, speed, opacity){ 
  /* 
   * 参数说明 
   * elem==>需要淡入的元素 
   * speed==>淡入速度,正整数(可选) 
   * opacity==>淡入到指定的透明度,0~100(可选) 
   */ 
  speedspeed = speed || 20; 
  opacityopacity = opacity || 100; 
  //显示元素,并将元素值为0透明度(不可见) 
  elem.style.display = 'block'; 
  iBase.SetOpacity(elem, 0); 
  //初始化透明度变化值为0 
  var val = 0; 
  //循环将透明值以5递增,即淡入效果 
  (function(){ 
   iBase.SetOpacity(elem, val); 
   val += 5; 
   if (val <= opacity) { 
    setTimeout(arguments.callee, speed) 
   } 
  })(); 
 } 
  
 //淡出效果(含淡出到指定透明度) 
 function fadeOut(elem, speed, opacity){ 
  /* 
   * 参数说明 
   * elem==>需要淡入的元素 
   * speed==>淡入速度,正整数(可选) 
   * opacity==>淡入到指定的透明度,0~100(可选) 
   */ 
  speedspeed = speed || 20; 
  opacityopacity = opacity || 0; 
  //初始化透明度变化值为0 
  var val = 100; 
  //循环将透明值以5递减,即淡出效果 
  (function(){ 
   iBase.SetOpacity(elem, val); 
   val -= 5; 
   if (val >= opacity) { 
    setTimeout(arguments.callee, speed); 
   }else if (val < 0) { 
    //元素透明度为0后隐藏元素 
    elem.style.display = 'none'; 
   } 
  })(); 
 } 

Rendering:

Core code, you can

copy the code directly to see the effect

 
 
 
 
原生JS实现淡入淡出效果 
 
<script> 
window.onload = function(){ 
 //底层共用 
 var iBase = { 
  Id: function(name){ 
   return document.getElementById(name); 
  }, 
  //设置元素透明度,透明度值按IE规则计,即0~100 
  SetOpacity: function(ev, v){ 
   ev.filters &#63; ev.style.filter = 'alpha(opacity=' + v + ')' : ev.style.opacity = v / 100; 
  } 
 } 
 //淡入效果(含淡入到指定透明度) 
 function fadeIn(elem, speed, opacity){ 
  /* 
   * 参数说明 
   * elem==&gt;需要淡入的元素 
   * speed==&gt;淡入速度,正整数(可选) 
   * opacity==&gt;淡入到指定的透明度,0~100(可选) 
   */ 
  speedspeed = speed || 20; 
  opacityopacity = opacity || 100; 
  //显示元素,并将元素值为0透明度(不可见) 
  elem.style.display = 'block'; 
  iBase.SetOpacity(elem, 0); 
  //初始化透明度变化值为0 
  var val = 0; 
  //循环将透明值以5递增,即淡入效果 
  (function(){ 
   iBase.SetOpacity(elem, val); 
   val += 5; 
   if (val &lt;= opacity) { 
    setTimeout(arguments.callee, speed) 
   } 
  })(); 
 } 
  
 //淡出效果(含淡出到指定透明度) 
 function fadeOut(elem, speed, opacity){ 
  /* 
   * 参数说明 
   * elem==&gt;需要淡入的元素 
   * speed==&gt;淡入速度,正整数(可选) 
   * opacity==&gt;淡入到指定的透明度,0~100(可选) 
   */ 
  speedspeed = speed || 20; 
  opacityopacity = opacity || 0; 
  //初始化透明度变化值为0 
  var val = 100; 
  //循环将透明值以5递减,即淡出效果 
  (function(){ 
   iBase.SetOpacity(elem, val); 
   val -= 5; 
   if (val &gt;= opacity) { 
    setTimeout(arguments.callee, speed); 
   }else if (val &lt; 0) { 
    //元素透明度为0后隐藏元素 
    elem.style.display = 'none'; 
   } 
  })(); 
 } 
  
  
 var btns = iBase.Id('demo').getElementsByTagName('input'); 
  
 btns[0].onclick = function(){ 
  fadeIn(iBase.Id('fadeIn')); 
 } 
 btns[1].onclick = function(){ 
  fadeOut(iBase.Id('fadeOut'),40); 
 } 
 btns[2].onclick = function(){ 
  fadeOut(iBase.Id('fadeTo'), 20, 10); 
 } 
  
} 
</script> 
 
 
 
 

脚本之家是国内专业的网站建设资源、脚本编程学习类网站,提供asp、php、asp.net、javascript、jquery、vbscript、dos批处理、网页制作、网络编程、网站建设等编程资料。

脚本之家

脚本之家是国内专业的网站建设资源、脚本编程学习类网站,提供asp、php、asp.net、javascript、jquery、vbscript、dos批处理、网页制作、网络编程、网站建设等编程资料。

脚本之家

脚本之家是国内专业的网站建设资源、脚本编程学习类网站,提供asp、php、asp.net、javascript、jquery、vbscript、dos批处理、网页制作、网络编程、网站建设等编程资料。

The above is all the code for realizing the fade-in and fade-out effect in native js. I hope it will be helpful to everyone's learning.

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
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment