<div class="container">
<div class="img-container">
<img src="image/1.jpg">
</div>
<ul class="carousel">
<li><img src="image/1.jpg"></li>
<li><img src="image/2.jpg"></li>
<li><img src="image/3.jpg"></li>
</ul>
<div class="prev"></div>
<div class="next"></div>
</div>
其中,`.container` 是整個輪播的容器,`.img-container` 用于顯示當前圖片,`.carousel` 是圖片列表,`.prev` 和 `.next` 是向左和向右的按鈕。
接著,我們需要為輪播添加一些簡單的 CSS 樣式來控制它的外觀。.container {
position: relative;
width: 800px;
height: 400px;
margin: 0 auto;
overflow: hidden;
}
.img-container {
position: absolute;
width: 100%;
height: 100%;
text-align: center;
}
.carousel {
position: absolute;
list-style: none;
padding: 0;
margin: 0;
}
.carousel li {
float: left;
width: 800px;
height: 400px;
text-align: center;
}
.carousel li img {
width: 100%;
height: auto;
}
.prev, .next {
position: absolute;
top: 50%;
width: 30px;
height: 30px;
margin-top: -15px;
background-color: #333;
cursor: pointer;
}
.prev {
left: 0;
}
.next {
right: 0;
}
現(xiàn)在,我們添加一些 JavaScript 代碼來控制輪播的動畫效果。window.onload = function() {
var carousel = document.querySelector('.carousel');
var imgContainer = document.querySelector('.img-container');
var prev = document.querySelector('.prev');
var next = document.querySelector('.next');
var imgWidth = document.querySelector('.carousel li').offsetWidth;
var currentIndex = 0;
carousel.style.width = imgWidth * carousel.children.length + 'px';
// 向左滑
prev.addEventListener('click', function() {
if (currentIndex >= 1) {
currentIndex--;
var newLeft = -currentIndex * imgWidth + 'px';
carousel.style.left = newLeft;
imgContainer.innerHTML = carousel.children[currentIndex].innerHTML;
} else {
currentIndex = carousel.children.length - 1;
var newLeft = -currentIndex * imgWidth + 'px';
carousel.style.left = newLeft;
imgContainer.innerHTML = carousel.children[currentIndex].innerHTML;
}
});
// 向右滑
next.addEventListener('click', function() {
if (currentIndex< carousel.children.length - 1) {
currentIndex++;
var newLeft = -currentIndex * imgWidth + 'px';
carousel.style.left = newLeft;
imgContainer.innerHTML = carousel.children[currentIndex].innerHTML;
} else {
currentIndex = 0;
var newLeft = -currentIndex * imgWidth + 'px';
carousel.style.left = newLeft;
imgContainer.innerHTML = carousel.children[currentIndex].innerHTML;
}
});
};
完整的 HTML5版輪播代碼就此完成了。現(xiàn)在,你可以將它加入你的網(wǎng)站,讓你的網(wǎng)站更加吸引人。