JS特效——广告图由左往右滚动
时间: 2023-09-03 09:07:03 浏览: 59
你可以使用CSS和JavaScript来实现广告图由左往右滚动的特效。
首先,在HTML文件中创建一个包含广告图的容器,如下所示:
```html
<div class="ad-container">
<img src="ad1.jpg">
<img src="ad2.jpg">
<img src="ad3.jpg">
</div>
```
然后,在CSS文件中设置容器的宽度和高度,并将其中的图片设置为浮动状态,如下所示:
```css
.ad-container {
width: 500px;
height: 200px;
overflow: hidden;
}
.ad-container img {
width: 500px;
height: 200px;
float: left;
}
```
接下来,在JavaScript文件中编写代码,实现广告图由左往右滚动的特效。首先,获取广告图容器以及其中的图片元素,如下所示:
```javascript
var adContainer = document.querySelector('.ad-container');
var adImgs = adContainer.querySelectorAll('img');
```
然后,使用定时器实现轮播特效。每隔一段时间,将容器向左移动一张图片的宽度,并将第一张图片移动到最后,如下所示:
```javascript
var currentIndex = 0; // 当前显示的图片索引
setInterval(function() {
var imgWidth = adImgs[0].offsetWidth; // 获取图片的宽度
adContainer.style.transform = 'translateX(-' + imgWidth * currentIndex + 'px)';
currentIndex++;
if (currentIndex >= adImgs.length) {
currentIndex = 0;
adContainer.style.transform = 'translateX(0)';
}
}, 3000); // 每隔3秒钟切换一次图片
```
最终效果就是,广告图会自动滚动,每隔3秒钟显示下一张图片,直到所有图片都显示完毕后,再从第一张图片重新开始。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)