不少网站会在首页中加入轮播图的效果,如果,我们也想要在自己开发的网站页面中实现这个效果,具体该如何操作呢?接下来,济南网站建设小编news.hcsw666.com/就为大家带来一个JavaScript实现轮播图的小案例,有兴趣的小伙伴可以过来参考一下。
关键代码:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>JS轮播图效果</title>
<style>
* {
margin: 0;
padding: 0;
list-style: none;
}
/* 轮播容器 */
.banner {
width: 600px;
height: 350px;
margin: 50px auto;
overflow: hidden;
position: relative;
}
/* 图片列表横向排列 */
.imgList {
width: 3000px;
height: 350px;
position: absolute;
left: 0;
top: 0;
}
.imgList li {
float: left;
}
.imgList img {
width: 600px;
height: 350px;
}
/* 左右箭头 */
.left,.right {
width: 40px;
height: 60px;
background: rgba(0,0,0,0.4);
color: #fff;
font-size: 24px;
text-align: center;
line-height: 60px;
position: absolute;
top: 50%;
margin-top: -30px;
cursor: pointer;
z-index: 10;
}
.left {left: 0;}
.right {right: 0;}
/* 底部小圆点 */
.point {
position: absolute;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
}
.point li {
width: 12px;
height: 12px;
border-radius: 50%;
background: #ccc;
float: left;
margin: 0 5px;
cursor: pointer;
}
.point li.active {
background: red;
}
</style>
</head>
<body>
<div class="banner" id="banner">
<!-- 轮播图片 -->
<ul class="imgList" id="imgList">
<li><img src="/600/350?random=1" alt=""></li>
<li><img src="/600/350?random=2" alt=""></li>
<li><img src="/600/350?random=3" alt=""></li>
<li><img src="/600/350?random=4" alt=""></li>
</ul>
<!-- 左右按钮 -->
<div class="left" id="leftBtn"><</div>
<div class="right" id="rightBtn">></div>
<!-- 小圆点 -->
<ul class="point" id="pointList">
<li class="active"></li>
<li></li>
<li></li>
<li></li>
</ul>
</div>
<script>
// 获取元素
let banner = document.getElementById('banner');
let imgList = document.getElementById('imgList');
let leftBtn = document.getElementById('leftBtn');
let rightBtn = document.getElementById('rightBtn');
let pointList = document.querySelectorAll('#pointList li');
let index = 0;
let imgWidth = 600;
let timer = null;
// 切换小圆点样式
function changePoint(){
for(let i=0;i<pointList.length;i++){
pointList[i].className = '';
}
pointList[index].className = 'active';
}
// 滚动切换图片
function moveImg(){
imgList.style.left = -index * imgWidth + 'px';
changePoint();
}
// 下一张
function nextImg(){
index++;
if(index >= pointList.length){
index = 0;
}
moveImg();
}
// 上一张
function prevImg(){
index--;
if(index < 0){
index = pointList.length - 1;
}
moveImg();
}
// 自动播放
function autoPlay(){
timer = setInterval(nextImg,2000);
}
autoPlay();
// 鼠标移入暂停 移出继续播放
banner.onmouseover = function(){
clearInterval(timer);
}
banner.onmouseout = function(){
autoPlay();
}
// 左右点击事件
rightBtn.onclick = nextImg;
leftBtn.onclick = prevImg;
// 点击小圆点切换
for(let i=0;i<pointList.length;i++){
pointList[i].onclick = function(){
index = i;
moveImg();
}
}
</script>
</body>
</html>
评论