html5 实现图片自动播放按钮
时间: 2023-10-15 22:08:12 浏览: 45
你可以使用HTML5的`<video>`标签和JavaScript来实现图片的自动播放功能。具体实现步骤如下:
1. 首先在HTML中定义一个`<video>`标签,并在其中添加多个`<source>`标签来指定不同格式的图片文件。
```html
<video id="slideshow" width="800" height="600">
<source src="image1.jpg" type="image/jpeg">
<source src="image2.png" type="image/png">
<source src="image3.gif" type="image/gif">
</video>
```
2. 在JavaScript中定义一个计时器,并在每个固定的时间间隔内更改`<video>`标签的`src`属性,以达到图片轮播的效果。
```javascript
var slideshow = document.getElementById('slideshow');
var sources = ['image1.jpg', 'image2.png', 'image3.gif'];
var index = 0;
var timer = setInterval(function() {
slideshow.src = sources[index];
index = (index + 1) % sources.length;
}, 3000);
```
3. 添加一个`<button>`标签来控制图片的自动播放和暂停。
```html
<button id="playpause">播放/暂停</button>
```
4. 在JavaScript中给`<button>`标签添加点击事件,以控制计时器的启停。
```javascript
var playpause = document.getElementById('playpause');
playpause.addEventListener('click', function() {
if (timer) {
clearInterval(timer);
timer = null;
playpause.innerHTML = '播放';
} else {
timer = setInterval(function() {
slideshow.src = sources[index];
index = (index + 1) % sources.length;
}, 3000);
playpause.innerHTML = '暂停';
}
});
```
这样就可以实现一个简单的图片自动播放功能,并且可以通过按钮来控制自动播放和暂停。