Home  >  Article  >  Web Front-end  >  Use js to achieve image carousel effect

Use js to achieve image carousel effect

王林
王林forward
2020-05-09 09:17:462523browse

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>

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>

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!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete