Home Web Front-end Front-end Q&A JavaScript implements automatic picture playback

JavaScript implements automatic picture playback

May 16, 2023 pm 01:22 PM

Nowadays, with the continuous development of Internet technology, web design has become a very important industry. As a very important element, pictures are often used in page design to beautify the page, enhance the effect of information transmission, and attract the user's attention. Presenting some dynamic elements on the page can not only enrich the content of the page, but also provide users with a more intuitive sensory effect and a better user experience when browsing. This article will introduce how JavaScript implements automatic image playback.

1. Principle of automatic carousel

Picture carousel, as the name suggests, allows multiple pictures to be played and switched automatically. The principle of automatic carousel is realized with the help of JavaScript timer: when the number of pages of the carousel is determined, the setInterval() function is used to switch pictures regularly; if the carousel is infinite, setTimeout() is used to implement recursive calls to achieve the carousel effect. .

2. HTML structure

To implement automatic carousel, you need to create a looping container and image in HTML, as follows:

<div class="carousel-container">
  <img src="images/pic1.png" alt="image 1">
  <img src="images/pic2.png" alt="image 2">
  <img src="images/pic3.png" alt="image 3">
</div>
Copy after login

3. CSS style

Set the style of the carousel container as follows:

.carousel-container{
  width: 100%;
  height: 500px;
  position: relative;
  overflow: hidden;
}
.carousel-container img{
  width: 100%;
  height: auto;
  position: absolute;
  top: 0;
  left: 0;
  opacity: 0;
  transition: all 0.6s ease-in-out;
}
.carousel-container img.active{
  opacity: 1; 
}
Copy after login

4. Implement carousel with JavaScript

1. Get the image and container

var carouselContainer = document.querySelector('.carousel-container');
var carouselImgs = carouselContainer.querySelectorAll('img');
Copy after login

2. Initialization Carousel

Before starting the carousel, you can add a class name "active" to the first picture, and set a counter index to represent the current carousel picture, so that you can switch to the next one in the next step. picture.

var index = 0;
carouselImgs[index].classList.add('active');
Copy after login
  1. Set the timer

During the carousel process, you need to switch a picture at a certain time. Here are two implementation methods: infinite carousel and Limited rotation. The difference lies in whether to restart the traversal from the beginning after all the image traversals are completed.

Infinite carousel:

setInterval(function(){
  index++;
  if(index >= carouselImgs.length){
    index = 0;
  }
  carouselImgs.forEach(function(img){
    img.classList.remove('active');
  });
  carouselImgs[index].classList.add('active');
}, 3000);
Copy after login

Limited carousel:

var timer = setInterval(function(){
  index++;
  if(index >= carouselImgs.length){
    clearInterval(timer);
    return;
  }
  carouselImgs.forEach(function(img){
    img.classList.remove('active');
  });
  carouselImgs[index].classList.add('active');
}, 3000);
Copy after login

As you can see here, by setting the counter index, you can ensure that the corresponding position is traversed each time, and at the same time We set a timer to rotate the next image every 3 seconds.

4. Add event listener

Some users may want to click on the picture to jump to the relevant page. In this case, we need to add event listener to the picture.

carouselImgs.forEach(function(img){
  img.addEventListener('click', function(e){
    var targetURL = e.target.getAttribute('data-href');
    if(targetURL){
      window.location.href=targetURL;
    }
  });
});
Copy after login

Here, we monitor the user's click behavior through event monitoring, and obtain the link corresponding to the image through the "getAttribute()" method, so that clicking on the image jumps to the target page.

5. Summary

After the above steps, we can successfully achieve the effect of automatic image rotation. However, it should be noted that carousel images cannot be used on all pages. Only appropriate scenarios and appropriate designs can produce good results. The automatic image carousel effect achieved through the above method also has certain limitations. When there are multiple carousel images on the page at the same time, conflicts may exist and affect the execution of the program. Therefore, we need to make reasonable adjustments and uses in practical applications to produce the best results.

The above is the detailed content of JavaScript implements automatic picture playback. For more information, please follow other related articles on the PHP Chinese website!

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

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

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How do you connect React components to the Redux store using connect()? How do you connect React components to the Redux store using connect()? Mar 21, 2025 pm 06:23 PM

Article discusses connecting React components to Redux store using connect(), explaining mapStateToProps, mapDispatchToProps, and performance impacts.

React's Role in HTML: Enhancing User Experience React's Role in HTML: Enhancing User Experience Apr 09, 2025 am 12:11 AM

React combines JSX and HTML to improve user experience. 1) JSX embeds HTML to make development more intuitive. 2) The virtual DOM mechanism optimizes performance and reduces DOM operations. 3) Component-based management UI to improve maintainability. 4) State management and event processing enhance interactivity.

How do you define routes using the <Route> component? How do you define routes using the <Route> component? Mar 21, 2025 am 11:47 AM

The article discusses defining routes in React Router using the &lt;Route&gt; component, covering props like path, component, render, children, exact, and nested routing.

What are the limitations of Vue 2's reactivity system with regard to array and object changes? What are the limitations of Vue 2's reactivity system with regard to array and object changes? Mar 25, 2025 pm 02:07 PM

Vue 2's reactivity system struggles with direct array index setting, length modification, and object property addition/deletion. Developers can use Vue's mutation methods and Vue.set() to ensure reactivity.

What are Redux reducers? How do they update the state? What are Redux reducers? How do they update the state? Mar 21, 2025 pm 06:21 PM

Redux reducers are pure functions that update the application's state based on actions, ensuring predictability and immutability.

What are Redux actions? How do you dispatch them? What are Redux actions? How do you dispatch them? Mar 21, 2025 pm 06:21 PM

The article discusses Redux actions, their structure, and dispatching methods, including asynchronous actions using Redux Thunk. It emphasizes best practices for managing action types to maintain scalable and maintainable applications.

What are the benefits of using TypeScript with React? What are the benefits of using TypeScript with React? Mar 27, 2025 pm 05:43 PM

TypeScript enhances React development by providing type safety, improving code quality, and offering better IDE support, thus reducing errors and improving maintainability.

How can you use useReducer for complex state management? How can you use useReducer for complex state management? Mar 26, 2025 pm 06:29 PM

The article explains using useReducer for complex state management in React, detailing its benefits over useState and how to integrate it with useEffect for side effects.

See all articles