帮我用html写一个图片轮播样式,要求中间图片放大,两边缩小,轮播效果
时间: 2024-03-26 17:38:28 浏览: 116
好的,我可以帮你写一个简单的图片轮播样式,代码如下:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>图片轮播</title>
<style>
.container {
display: flex;
justify-content: center;
align-items: center;
height: 500px;
}
.slider {
display: flex;
position: relative;
width: 800px;
height: 400px;
border: 1px solid #ccc;
box-shadow: 0px 0px 10px #ccc;
overflow: hidden;
}
.slide {
position: absolute;
display: flex;
justify-content: center;
align-items: center;
top: 0;
left: 0;
width: 100%;
height: 100%;
transition: all 0.5s ease-in-out;
z-index: 1;
}
.slide img {
max-width: 100%;
max-height: 100%;
object-fit: cover;
}
.slide.center {
transform: scale(1.2);
z-index: 2;
}
.slide.left {
transform: translateX(-200px) scale(0.8);
}
.slide.right {
transform: translateX(200px) scale(0.8);
}
</style>
</head>
<body>
<div class="container">
<div class="slider">
<div class="slide center">
<img src="https://picsum.photos/800/400?random=1" alt="slide 1">
</div>
<div class="slide left">
<img src="https://picsum.photos/800/400?random=2" alt="slide 2">
</div>
<div class="slide right">
<img src="https://picsum.photos/800/400?random=3" alt="slide 3">
</div>
</div>
</div>
<script>
var center = document.querySelector('.center');
var left = document.querySelector('.left');
var right = document.querySelector('.right');
function slideLeft() {
center.classList.remove('center');
center.classList.add('right');
right.classList.remove('right');
right.classList.add('center');
left.classList.remove('left');
left.classList.add('right');
var newLeft = document.createElement('div');
newLeft.classList.add('slide', 'left');
newLeft.innerHTML = '<img src="https://picsum.photos/800/400?random=' + (Math.floor(Math.random() * 100) + 4) + '" alt="slide">';
document.querySelector('.slider').appendChild(newLeft);
}
function slideRight() {
center.classList.remove('center');
center.classList.add('left');
left.classList.remove('left');
left.classList.add('center');
right.classList.remove('right');
right.classList.add('left');
var newRight = document.createElement('div');
newRight.classList.add('slide', 'right');
newRight.innerHTML = '<img src="https://picsum.photos/800/400?random=' + (Math.floor(Math.random() * 100) + 4) + '" alt="slide">';
document.querySelector('.slider').appendChild(newRight);
}
setInterval(slideLeft, 5000);
document.addEventListener('keydown', function(event) {
if (event.keyCode === 37) {
slideRight();
}
if (event.keyCode === 39) {
slideLeft();
}
});
</script>
</body>
</html>
```
这段代码使用了 flex 布局和绝对定位来实现图片轮播效果。其中,中间的图片放大,两边的图片缩小,可以通过 `.slide` 的 `transform` 属性来实现。轮播效果可以通过 JS 来实现,这里使用了 `setInterval` 函数来定时轮播图片,同时也可以通过键盘左右箭头来切换图片。
希望这个样式能够满足你的需求,如果有任何问题,可以随时向我提问哦!
阅读全文