使用js实现轮播图
今天用js写了一下轮播图 简单的方法:修改图片名称为feng1.jpg、feng2.jpg这样的 在js中只用改变名称为1、2、3就能切换图片。 实现功能:1自动轮播、2手动轮播,左右切换、3鼠标指针悬停在图片上时停止轮播,鼠标指针移开继续轮播 实现方法:1.切换图片的函数+定时器实现自动轮播、2点击切换图片的函数、3悬停clear定时器,鼠标指针离开 创建定时器
效果图
代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>轮播图1</title>
<style>
.lunbo {
width: 900px;
height: 400px;
margin: 100px auto;
}
.lunbo img {
width: 100%;
height: 100%;
}
.tleft{
position: absolute;
top: 230px;
left: 330px;
font-size: 80px;
color: aliceblue;
cursor: pointer;
}
.tright{
position: absolute;
top: 230px;
right: 330px;
font-size: 80px;
color: aliceblue;
cursor: pointer;
}
</style>
</head>
<body>
<a class="tleft" onclick="toleft()"><</a>
<div class="lunbo">
<img id="lunbo_img" src="img/feng1.jpg" onmouseover="stopimg()" onmouseout="startimg()">
</div>
<span class="tright" onclick="toright()">></span>
<script>
var index = 1;
var time=setInterval(lunbo,2000);
function lunbo() {
index++;
if (index > 3) {
index = 1;
}
var img = document.getElementById("lunbo_img");
img.src = "img/feng" + index + ".jpg";
}
var toleft=function(){
clearInterval(time);
if(index==1){
index=3
}
else{
index--;
}
let img = document.getElementById("lunbo_img");
img.src="img/feng" + index + ".jpg";
time=setInterval(lunbo,2000);
}
var toright=function(){
clearInterval(time);
if(index==3){
index=1
}
else{
index++;
}
let img = document.getElementById("lunbo_img");
img.src="img/feng" + index + ".jpg";
time=setInterval(lunbo,2000);
}
var stopimg=function(){
clearInterval(time);
}
var startimg=function(){
time=setInterval(lunbo,2000);
}
</script>
</body>
</html>
|