HTML中左右
图片滚动
代码
HTML中实现
图片滚动的
方法有很多种,其中最常见的是左右滚动的方式。下面将介绍一种简单的实现左右
图片滚动的
代码。
首先,在HTML文档中
添加下面的
代码:
``` HTML

```
其中,`.carousel`为最外层的盒子,`.carousel-images`为
图片展示区域。
接下来,在CSS
文件中
添加以下样式:
``` CSS
.carousel {
width: 80%;
overflow: hidden;
margin: 0 auto;
}
.carousel-images {
white-space:
Nowrap;
transition: transform 0.5s ease;
}
.carousel-images img {
display: inline-block;
height: 100%;
width: auto;
max-height: 100%;
margin-right: 10px;
}
```
其中,`.carousel`的`width`为整个盒子的宽度,`overflow`为隐藏超出部分,`margin`为上下居中。`.carousel-images`的`white-space`
属性为`
Nowrap`,表示不允许折行,实现左右滚动。`.carousel-images img`为每张
图片的样式,`
display`为`inline-block`,让
图片显示在同一行,`height`为占满整个盒子高度,`width`为自适应,`max-height`为
图片的最大高度,`margin-right`为控制
图片之
间的间距。
最后,在JavaScript
文件中
添加以下
代码:
``` JavaScript
const carouselImages = document.querySelector('.carousel-images');
const images = document.querySelectorAll('.carousel-images img');
let counter = 1;
const size = images[0].clientWidth;
carouselImages.style.transform = 'translateX(' + (-size * counter) + 'px)';
setInterval(() => {
carouselImages.style.transition = 'transform 0.5s ease';
counter++;
carouselImages.style.transform = 'translateX(' + (-size * counter) + 'px)';
},5000);
carouselImages.addEventListener('
transitionend',() => {
if (images[counter].id === 'last-clone') {
carouselImages.style.transition = 'none';
counter = images.length - 2;
carouselImages.style.transform = 'translateX(' + (-size * counter) + 'px)';
}
if (images[counter].id === 'f
irst-clone') {
carouselImages.style.transition = 'none';
counter = images.length - counter;
carouselImages.style.transform = 'translateX(' + (-size * counter) + 'px)';
}
});
```
其中,`const carouselImages`为最外层盒子,`const images`为所有
图片的集合,`let counter`为计数器,`const size`为每张
图片的宽度。`carouselImages.style.transform`为初始化
显示第一张图片,`setInterval`为定时器,每5秒滚动一张
图片,`carouselImages.addEventListener`为监听动画完成状态,当滚动到最后一张或第一张时,无缝滚动到相应的位置。
总之,通过以上
代码,您就可以在HTML中实现
一个左右
图片滚动的
效果啦!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。