javaweb 实现轮播图,装在div盒子里
时间: 2023-07-13 11:39:41 浏览: 127
jQuery实现轮播图及其原理详解
以下是一个基于JavaWeb的简单轮播图实现,同时装在了一个div盒子里:
1. HTML文件:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaWeb轮播图</title>
<style type="text/css">
.carousel {
width: 800px;
height: 600px;
margin: 0 auto;
position: relative;
overflow: hidden;
border: 1px solid #ccc;
}
.carousel img {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: none;
}
.carousel img.active {
display: block;
}
.carousel .previous-button, .carousel .next-button {
position: absolute;
top: 50%;
transform: translateY(-50%);
background: none;
border: none;
font-size: 24px;
color: #fff;
text-shadow: 1px 1px 1px #000;
cursor: pointer;
z-index: 1;
}
.carousel .previous-button {
left: 0;
}
.carousel .next-button {
right: 0;
}
</style>
</head>
<body>
<div class="carousel">
<img src="images/1.jpg" class="active">
<img src="images/2.jpg">
<img src="images/3.jpg">
<button class="previous-button">❮</button>
<button class="next-button">❯</button>
</div>
<script type="text/javascript">
var carousel = document.querySelector('.carousel');
var images = carousel.querySelectorAll('img');
var previousButton = carousel.querySelector('.previous-button');
var nextButton = carousel.querySelector('.next-button');
var currentIndex = 0;
previousButton.addEventListener('click', function() {
images[currentIndex].classList.remove('active');
currentIndex--;
if (currentIndex < 0) {
currentIndex = images.length - 1;
}
images[currentIndex].classList.add('active');
});
nextButton.addEventListener('click', function() {
images[currentIndex].classList.remove('active');
currentIndex++;
if (currentIndex >= images.length) {
currentIndex = 0;
}
images[currentIndex].classList.add('active');
});
var timer = setInterval(function() {
images[currentIndex].classList.remove('active');
currentIndex++;
if (currentIndex >= images.length) {
currentIndex = 0;
}
images[currentIndex].classList.add('active');
}, 3000);
carousel.addEventListener('mouseover', function() {
clearInterval(timer);
});
carousel.addEventListener('mouseout', function() {
timer = setInterval(function() {
images[currentIndex].classList.remove('active');
currentIndex++;
if (currentIndex >= images.length) {
currentIndex = 0;
}
images[currentIndex].classList.add('active');
}, 3000);
});
</script>
</body>
</html>
```
2. CSS文件:
```css
.carousel {
width: 800px;
height: 600px;
margin: 0 auto;
position: relative;
overflow: hidden;
border: 1px solid #ccc;
}
.carousel img {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: none;
}
.carousel img.active {
display: block;
}
.carousel .previous-button,
.carousel .next-button {
position: absolute;
top: 50%;
transform: translateY(-50%);
background: none;
border: none;
font-size: 24px;
color: #fff;
text-shadow: 1px 1px 1px #000;
cursor: pointer;
z-index: 1;
}
.carousel .previous-button {
left: 0;
}
.carousel .next-button {
right: 0;
}
```
这个实现使用了HTML、CSS和JavaScript来实现轮播图,并通过CSS将轮播图装在了一个div盒子里。
阅读全文