html5 实现图片自动轮播,并且不需要手动翻页的按钮,所有代码放在一个html文件里,请把完整代码写出来
时间: 2024-05-29 18:13:52 浏览: 82
<!DOCTYPE html>
<html>
<head>
<title>自动轮播图片</title>
<style>
.carousel {
width: 500px;
height: 300px;
margin: 0 auto;
position: relative;
overflow: hidden;
}
.carousel ul {
list-style: none;
position: relative;
margin: 0;
padding: 0;
height: 300px;
}
.carousel ul li {
position: relative;
display: block;
float: left;
margin: 0;
padding: 0;
width: 500px;
height: 300px;
background: #ccc;
text-align: center;
line-height: 300px;
font-size: 200px;
}
.carousel .btn {
position: absolute;
top: 50%;
margin-top: -15px;
width: 30px;
height: 30px;
background: #999;
text-align: center;
line-height: 30px;
cursor: pointer;
opacity: 0.5;
color: #fff;
}
.carousel .btn:hover {
opacity: 0.8;
}
.carousel .btn.next {
right: 0;
}
</style>
</head>
<body>
<div class="carousel">
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
</div>
<script type="text/javascript">
var carousel = document.querySelector('.carousel');
var ul = document.querySelector('.carousel ul');
var li = document.querySelectorAll('.carousel ul li');
var btnPrev = document.createElement('div');
var btnNext = document.createElement('div');
var imgWidth = li[0].offsetWidth;
var imgCount = li.length;
var currentImg = 1;
// 设置按钮样式
btnPrev.classList.add('btn', 'prev');
btnNext.classList.add('btn', 'next');
btnPrev.innerHTML = '<';
btnNext.innerHTML = '>';
// 将按钮添加到页面
carousel.appendChild(btnPrev);
carousel.appendChild(btnNext);
// 设置ul的宽度
ul.style.width = imgWidth * imgCount + 'px';
// 设置无缝滚动
ul.innerHTML += ul.innerHTML;
// 绑定事件
btnPrev.onclick = function () {
if (currentImg === 1) {
currentImg = imgCount;
ul.style.left = -imgWidth * (imgCount - 1) + 'px';
} else {
currentImg--;
ul.style.left = parseInt(ul.style.left) + imgWidth + 'px';
}
};
btnNext.onclick = function () {
if (currentImg === imgCount) {
currentImg = 1;
ul.style.left = 0;
} else {
currentImg++;
ul.style.left = parseInt(ul.style.left) - imgWidth + 'px';
}
};
// 自动播放
setInterval(function () {
btnNext.onclick();
}, 2000);
</script>
</body>
</html>
阅读全文