With the development of Internet applications, the beauty and interactivity of websites have become important factors in attracting visitors. In web design, the use of images is indispensable. Setting up an image transition effect on your page is a great way to grab the user's attention. In this article, we will use JavaScript to implement a simple image switching effect.
First, we need to create an HTML file. At the head of the file, we can add references to CSS styles and JavaScript scripts. Within the body tag, create a div element to wrap our image. As shown below:
In the CSS style, we set the width and height of the #img div element, and defined the position of the image as relative. Also set the position of each image to absolute so that they can be stacked together.
Here, we use the opacity attribute to set the transparency of the image. The active class represents the currently displayed image. When switching to the next image, we set the opacity value of the currently displayed image to 0, and then set the opacity value of the next image to 1. This creates a fading and emerging effect.
Next, we will create a JavaScript script file img_switch.js. The code is as follows:
var i = 0; // 初始化计数器 var images = document.querySelectorAll("#img img"); // 获取所有的图片元素 var len = images.length; // 获取图片的总数 function switchImg() { // 隐藏当前展示的图片 images[i].classList.remove("active"); // 获取下一个图片的索引位置 i = (i + 1) % len; // 显示下一张图片 images[i].classList.add("active"); } // 每隔5秒切换一次图片 setInterval(switchImg, 5000);
In this JavaScript script, we first define a counter variable i, then obtain all the picture elements and store them in the variable images. We also define the variable len to store the total number of pictures.
In the switchImg function, we first remove the active class of the currently displayed picture, then calculate the index position of the next picture, and add the active class to display the next picture. We use the setInterval function to call the switchImg function regularly to realize the function of automatically switching pictures.
Finally, we reference the JavaScript script in the HTML file to trigger the automatic switching effect.
This is how to use JavaScript to switch images. We can customize styles and scripts as needed to achieve cooler effects.
The above is the detailed content of Implement image switching using javascript. For more information, please follow other related articles on the PHP Chinese website!