Javascript 每隔几秒更改一次 HTML 页面中的图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13975891/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 15:19:09  来源:igfitidea点击:

Change image in HTML page every few seconds

javascripthtmlimagetimer

提问by user1834091

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.

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

回答by Adriano Repetti

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:

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

(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>

回答by Marcin Wasiluk

below will change link and banner every 10 seconds

下面将每 10 秒更改一次链接和横幅

   <script>
        var links = ["http://www.abc.com","http://www.def.com","http://www.ghi.com"];
        var images = ["http://www.abc.com/1.gif","http://www.def.com/2.gif","http://www.ghi.com/3gif"];
        var i = 0;
        var renew = setInterval(function(){
            if(links.length == i){
                i = 0;
            }
            else {
            document.getElementById("bannerImage").src = images[i]; 
            document.getElementById("bannerLink").href = links[i]; 
            i++;

        }
        },10000);
        </script>



<a id="bannerLink" href="http://www.abc.com" onclick="void window.open(this.href); return false;">
<img id="bannerImage" src="http://www.abc.com/1.gif" width="694" height="83" alt="some text">
</a>

回答by Paul Fleming

Change setTimeout("changeImage()", 30000);to setInterval("changeImage()", 30000);and remove var timerid = setInterval(changeImage, 30000);.

更改setTimeout("changeImage()", 30000);setInterval("changeImage()", 30000);并删除var timerid = setInterval(changeImage, 30000);.

回答by Oleg V. Volkov

As of current edited version of the post, you call setIntervalat each change's end, adding a new "changer" with each new iterration. That means after first run, there's one of them ticking in memory, after 100 runs, 100 different changers change image 100 times every second, completely destroying performance and producing confusing results.

从帖子的当前编辑版本开始,您setInterval在每次更改结束时调用,为每个新迭代添加一个新的“更改器”。这意味着第一次运行后,其中一个在内存中滴答作响,运行 100 次后,100 个不同的转换器每秒更改图像 100 次,完全破坏性能并产生混乱的结果。

You only need to "prime" setIntervalonce. Remove it from function and place it inside onloadinstead of direct function call.

您只需要“准备”setInterval一次。将其从函数中移除并将其放置在内部onload而不是直接函数调用。

回答by Alexis

You can load the images at the beginning and change the css attributes to show every image.

您可以在开始时加载图像并更改 css 属性以显示每个图像。

var images = array();
for( url in your_urls_array ){
   var img = document.createElement( "img" );
   //here the image attributes ( width, height, position, etc )
   images.push( img );
}

function player( position )
{
  images[position-1].style.display = "none" //be careful working with the first position
  images[position].style.display = "block";
  //reset position if needed
  timer = setTimeOut( "player( position )", time );
}

回答by cerberus

Best way to swap images with javascript with left vertical clickable thumbnails

用带有左垂直可点击缩略图的 javascript 交换图像的最佳方式

SCRIPT FILE: function swapImages() {

脚本文件:函数 swapImages() {

    window.onload = function () {
        var img = document.getElementById("img_wrap");
        var imgall = img.getElementsByTagName("img");
        var firstimg = imgall[0]; //first image
        for (var a = 0; a <= imgall.length; a++) {
            setInterval(function () {
                var rand = Math.floor(Math.random() * imgall.length);
                firstimg.src = imgall[rand].src;
            }, 3000);



            imgall[1].onmouseover = function () {
                 //alert("what");
                clearInterval();
                firstimg.src = imgall[1].src;


            }
            imgall[2].onmouseover = function () {
                clearInterval();
                firstimg.src = imgall[2].src;
            }
            imgall[3].onmouseover = function () {
                clearInterval();
                firstimg.src = imgall[3].src;
            }
            imgall[4].onmouseover = function () {
                clearInterval();
                firstimg.src = imgall[4].src;
            }
            imgall[5].onmouseover = function () {
                clearInterval();
                firstimg.src = imgall[5].src;
            }
        }

    }


}