search
HomeWeb Front-endJS TutorialHow to use JavaScript to achieve the fade-in effect of lazy loading of images?

如何使用 JavaScript 实现图片懒加载的淡入效果?

How to use JavaScript to achieve the fade-in effect of lazy loading of images?

In modern web design, in order to improve user experience and website performance, lazy loading of images has become a common technology. Lazy loading of images can reduce initial load time by delaying the loading of images until the user scrolls to where they are. Additionally, to further enhance the user experience, adding a fade-in effect can make the page smoother and more attractive. In this article, we will learn how to use JavaScript to implement the fade-in effect of lazy loading of images.

The first step is to determine which images need to be lazy loaded. Usually, we set the src attribute of the img tag to empty, and then save the real image address in a custom attribute, such as data-src. In this way, the image will not be loaded when the page is loaded. Only when the user scrolls to the location of the image, the real image address will be loaded and rendered.

<img class="lazy-img lazy"  src="/static/imghwm/default1.png"  data-src="path/to/image.jpg"  data- alt="Lazy Image">

Next, we need to add some JavaScript code to achieve the lazy loading effect. We will listen for user scroll events and check which images are within the viewable area. For pictures in the visible area, we assign their real address (that is, the value of the data-src attribute) to the src attribute to load the picture.

// 获取所有拥有lazy-img类的图片元素
const lazyImages = document.querySelectorAll('.lazy-img');

// 监听用户滚动事件
window.addEventListener('scroll', function() {
  // 循环遍历所有图片元素
  for (let i = 0; i < lazyImages.length; i++) {
    // 检查图片元素是否在可视区域内
    if (isInViewport(lazyImages[i])) {
      // 将真实的图片地址赋给src属性
      lazyImages[i].src = lazyImages[i].getAttribute('data-src');
      // 添加淡入效果
      lazyImages[i].classList.add('fade-in');
    }
  }
});

// 检查元素是否在可视区域内的函数
function isInViewport(element) {
  const rect = element.getBoundingClientRect();
  return (rect.top >= 0 && rect.left >= 0 && rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && rect.right <= (window.innerWidth || document.documentElement.clientWidth));
}

In the above code, we use an isInViewport() function to check whether the picture element is within the visible area. This function obtains the position information of the element by calling the getBoundingClientRect() method and compares it with the height and width of the window. Returns true if the element is within the visible area.

Finally, we can also add a fade-in effect to the image so that it displays smoothly on the page after loading. We add a fade-in class to the image element, so that after the image is loaded, the CSS transition effect will be triggered to achieve the fade-in animation effect.

.lazy-img {
  opacity: 0;
  transition: opacity 0.3s ease-in;
}

.lazy-img.fade-in {
  opacity: 1;
}

In the above code, we set the opacity of the image to 0 initially, and then gradually transition it to full opacity (i.e. 1) using a CSS transition effect. This process lasts for 0.3 seconds and is carried out in a gradual manner.

Through the above steps, we can use JavaScript to achieve the fade-in effect of lazy loading of images. Not only does this improve website performance and user experience, it also makes the website look smoother and more attractive. Hope this article helps you!

The above is the detailed content of How to use JavaScript to achieve the fade-in effect of lazy loading of images?. 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
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

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

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

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.