Home > Article > Web Front-end > How to implement image switching in javascript
Javascript method to implement image switching: first create a new file and use the img tag to create an image display; then use new Array() to create an array of image paths; then use the variable timeInterval to define the image switching time as 1 second; finally Realize scheduled switching of pictures.
The operating environment of this tutorial: Windows 7 system, JavaScript version 1.8.5, DELL G3 computer.
How to implement image switching using javascript:
Create a new html file, named test.html, to explain how to use javascript to implement scheduled image switching.
In test.html, use the img tag to create a picture display, and set its id attribute to obj, so that the element object can be obtained below.
In the script tag of the test.html page, use new Array() to create an array of image paths and put the file names of the three images in it.
In the script tag of the test.html page, use the variable timeInterval to define the image switching time as 1 second, and set it to execute once every second through the setInterval() timer method. changeImg() function.
In the changeImg() function, use the document.getElementById() method to obtain the img object, set an initial curIndex variable, and compare the names of the pictures through if statements to achieve continuous changes The name of the picture.
Note: The name of the picture must be an ordered number such as 0, 1, 2, etc.
In the changeImg() function, the image name obtained in the previous step is used to change the image path of img, and finally realizes the scheduled switching of images.
Open the test.html file in the browser to check the effect and achieve switching pictures every second.
Related free learning recommendations: javascript video tutorial
The above is the detailed content of How to implement image switching in javascript. For more information, please follow other related articles on the PHP Chinese website!