With the rapid development of the Internet, website production has become more and more popular, and carousel images are a very common website element that can make the website look more vivid and lively. How to implement a simple html carousel? let's see.
First, in the new HTML document, introduce a .css file and a .js file in the head, create a new div in the body, and add class and id attributes.
<head> <link rel="stylesheet" href="style.css"> <script src="script.js"></script> </head> <body> <div class="slider" id="slider"> <!--轮播图内容--> </div> </body>
Next, in the .css file, set the style of the carousel image. Taking the 1000×500 carousel image as an example, you need to set the size and position of the carousel image, as well as the width and height of the image. You also need to set the initial position and animation change time of the image in the carousel image.
.slider { width: 1000px; height: 500px; margin: 0 auto; overflow: hidden; position: relative; border: 2px solid #ddd; } .slider img { width: 1000px; height: 500px; position: absolute; top: 0; left: 0; opacity: 0; transition: opacity 500ms ease-in-out; } .slider img.active { opacity: 1; z-index: 1; }
In the .js file, add the carousel code. First, define a variable to track the currently displayed image. Then, set a timer to switch to the next image after 5000ms. Finally, update the current image's class so that the current image is added to the active class, thereby changing its opacity.
var slider = document.getElementById("slider"); var images = slider.getElementsByTagName("img"); var counter = 0; setInterval(function() { images[counter].classList.remove("active"); counter++; if (counter == images.length) { counter = 0; } images[counter].classList.add("active"); }, 5000);
Finally, you only need to add the image element in the slider div, as shown below:
<div class="slider" id="slider"> <img src="img1.jpg" class="active"> <img src="img2.jpg"> <img src="img3.jpg"> </div>
This is the process of implementing a simple html carousel image. As a commonly used element on websites, carousel images can not only add to the visual experience of the website, but also improve the user experience of the website. Start creating your own carousel!
The above is the detailed content of How to make html carousel image. For more information, please follow other related articles on the PHP Chinese website!