每隔几秒更改 HTML 页面中的图像 [英] Change image in HTML page every few seconds

查看:15
本文介绍了每隔几秒更改 HTML 页面中的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想每隔几秒更改一次图像,这是我的代码:

I want to change images every few seconds, this is my code:

<?xml version = "1.0" encoding = "utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns = "http://www.w3.org/1999/xhtml">
   <head>
      <title>change picture</title>
      <script type = "text/javascript">

    function changeImage()
    {
    var img = document.getElementById("img");
    img.src = images[x];
    x++;

    if(x >= images.length){
        x = 0;
    } 
   var timerid = setInterval(changeImage(), 1000);
}   }
var images = [], x = 0;
images[0] = "image1.jpg";
images[1] = "image2.jpg";
images[2] = "image3.jpg";

      </script>
   </head>
   <body onload = "changeImage()">
 <img id="img" src="startpicture.jpg">
   </body>
</html>

我的问题是它卡在第一张图片上!

My problem is its stuck on the first picture!

我也想尝试使用上一个和下一个按钮翻阅图片,但我不知道该怎么做.

I also wanted to try flipping through the pictures with previous and next buttons but I have no idea how to do that.

推荐答案

正如我在评论中发布的,您不需要同时使用 setTimeout()setInterval(),而且你也有一个语法错误(一个额外的 }).像这样更正您的代码:

As I posted in the comment you don't need to use both setTimeout() and setInterval(), moreover you have a syntax error too (the one extra }). Correct your code like this:

(编辑添加两个功能强制显示下一张/上一张图片)

(edited to add two functions to force the next/previous image to be shown)

<!DOCTYPE html>

<html>
   <head>
      <title>change picture</title>
      <script type = "text/javascript">
          function displayNextImage() {
              x = (x === images.length - 1) ? 0 : x + 1;
              document.getElementById("img").src = images[x];
          }

          function displayPreviousImage() {
              x = (x <= 0) ? images.length - 1 : x - 1;
              document.getElementById("img").src = images[x];
          }

          function startTimer() {
              setInterval(displayNextImage, 3000);
          }

          var images = [], x = -1;
          images[0] = "image1.jpg";
          images[1] = "image2.jpg";
          images[2] = "image3.jpg";
      </script>
   </head>

   <body onload = "startTimer()">
       <img id="img" src="startpicture.jpg"/>
       <button type="button" onclick="displayPreviousImage()">Previous</button>
       <button type="button" onclick="displayNextImage()">Next</button>
   </body>
</html>

这篇关于每隔几秒更改 HTML 页面中的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆