Home > Web Front-end > JS Tutorial > body text

Use js to achieve image carousel effect

王林
Release: 2020-05-09 09:17:46
forward
2600 people have browsed it

Use js to achieve image carousel effect

Analysis process:

Switch picture:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        function changeImg() {
            alert("123")
            var img222 = document.getElementById(img1);

            img222.src = "img/2.jpg";
        }
    </script>
 </head>
<body>
<input type="button" value="点击换图片" onclick="changeImg()">
<img src="img/1.jpg" id="img1">
</body>
</html>
Copy after login

Do one thing every three seconds:

window.setInterval (): Call a function or calculate an expression according to the specified period (in milliseconds)

setInterval("alert('123')",2000)

window does not need to be written, the first A variable needs to use "", and the "" inside needs to become ''

window.setTimeout(): Call a function or calculate an expression after a specified number of milliseconds

window.clearInterval( ):
window.setInterval() method or returns an id of type int. You can assign the id to window.clearInterval() to close
window.clearTimeout():

Specific code implementation :

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script>
			/* 当页面加载完成的时候, 动态切换图片
				 1.确定事件:
				 2.事件所要触发的函数
			 */
			var index = 1;			//切换图片的函数
			function changeAd(){				//获取要操作的img
				var img = document.getElementById("imgAd");
				img.src = "../img/"+(index%3+1)+".jpg";  //0,1,2    //1,2,3
				index++;
			}			
			function init(){				//启动定时器
				setInterval("changeAd()",3000);
			}
		</script>
	</head>
	<body onload="init()">
		<img src="../img/1.jpg" id="imgAd"/>
	</body>
</html>
Copy after login

Recommended tutorial: js entry tutorial

The above is the detailed content of Use js to achieve image carousel effect. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:cnblogs.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template