简体   繁体   English

如何在javascript和html中每5秒更改一次文本和图像

[英]how to change a text and image every 5 seconds in javascript and html

hey I wrote a JavaScript code and I managed to make the image change every few seconds but the text is changing alongside with the image but not the correct text is shown here is the code:嘿,我写了一个 JavaScript 代码,我设法每隔几秒钟更改一次图像,但文本与图像一起更改,但未显示正确的文本,这里是代码:

<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="UTF-8">
      <meta name="viewport"
            content="width=device-width, initial-scale=1.0">
      <link rel="stylesheet" href=
"https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
      <style>
         img{
         height: 500px;
         width: 450px;
         }
         h1{
         color: darkgreen;
         margin-top: 20px;
         font-family: Comic Sans MS, cursive, sans-serif;
         }
         .button{
         margin-left: 45%;
         }
      </style>
      <script>

     
      function changeImage() {
        var img = document.getElementById("img");
        img.src = images[x];
        x++;        
        if(x >= images.length) {
            x = 0;
        } 
       setTimeout("changeImage()", 6000);
     }
    
     function changeText() {
       var txt= document.getElementById("message");
       txt.textContent = text[y];
       y++;
       if(y>= text.length){
          y = 0;
       }
       setTimeout("changeText()", 6000);
    
     }
    
    
    var text = [], y=0;
    text[0] = "MSG1";
    text[1] = "MSG2";
    text[1] = "MSG3";
    setTimeout("changeText()", 6000);
    var images = [], x = 0;
    images[0] = "image1.jpg";
    images[1] = "image2.jpg";
    images[2] = "image3.jpg";
    setTimeout("changeImage()", 6000);

      </script>
   </head>
   <body>
      <div class="container">
         <div class="row">
            <div class="col-md-3"></div>
            <div class="col-md-6">
               <h1 id="message">
                   Hello
               </h1>
               <img  id="img"
                     src="image1.jpg"  >
            </div>
            <div class="col-md-3"></div>
         </div>
      </div>
   </body>
</html>

is there any efficient way to do it my goal is to make 3-5 images on an html webpage that change between each other every few seconds and each image has a different text above it有什么有效的方法可以做到这一点我的目标是在 html 网页上制作 3-5 张图片,这些图片每隔几秒钟就会相互更改一次,并且每张图片上方都有不同的文字

Combine your two functions into one, so both things happen at the same time:将您的两个功能合二为一,因此这两件事同时发生:

<script>
  function changeImageAndText() {
    var img = document.getElementById("img");
    img.src = images[x];
    var txt = document.getElementById("message");
    txt.textContent = text[x];
    x++;
    if (x >= images.length) {
      x = 0;
    }
    setTimeout("changeImageAndText()", 6000);
  }

  var text = [],
    images = [],
    x = 0;
  text[0] = "MSG1";
  text[1] = "MSG2";
  text[2] = "MSG3";
  images[0] = "image1.jpg";
  images[1] = "image2.jpg";
  images[2] = "image3.jpg";
  setTimeout("changeImageAndText()", 6000);

</script>

Instead of maintaining two arrays have one array of objects each of which contains image and text information.不是维护两个数组,而是拥有一个对象数组,每个对象都包含图像和文本信息。 You can then create markup containing both sets of information at once rather than relying on two functions.然后,您可以同时创建包含两组信息的标记,而不是依赖两个函数。

This working example uses images from dummyimage.com .这个工作示例使用来自dummyimage.com 的图像。

 const data = [ { image: 'https://dummyimage.com/100x100/666/ff0', text: 'Image 1' }, { image: 'https://dummyimage.com/100x100/222/ff0', text: 'Image 2' }, { image: 'https://dummyimage.com/100x100/fff/000', text: 'Image 3' }, { image: 'https://dummyimage.com/100x100/a45/000', text: 'Image 4' }, ]; // Cache the element const div = document.querySelector('div'); // `carousel` is the main function into which we // pass the data function carousel(data) { // `loop` is what `setTimeout` calls every second // We initialise `count` to 0 function loop(count = 0) { // Create the HTML using a template string const html = ` <figure> <img src="${data[count].image}" /> <figcaption>${data[count].text}</figcaption> </figure>`; // Add the markup to the div div.innerHTML = html; // Reset the count if we've reached the // end of the array, otherwise increment it if (count === data.length - 1) { count = 0; } else { ++count; } // Call `loop` every second with the // updated `count` variable setTimeout(loop, 1000, count); } loop(); } carousel(data);
 <div></div>

Additional information附加信息

The way I would do it is this:我会这样做:

const text = ["MSG1", "MSG2", "MSG3"];
const image = ["image1.jpg", "image2.jpg", "image3.jpg"];

const imageObj = document.GetElementById("img");
const textObj = document.GetElementById("message");

let counter = 0;

function ChangeImage() {
    if (counter == text.length) { 
        counter = 0;
    }

    textObj.innerText = text[counter];
    imageObj.src = image[counter];

    counter++;
}

setInterval(ChangeImage, 3000); // 3000 = 3 Seconds, 5000 = 5 seconds.

The main thing to remember is to reduce the amount of times you repeat yourself, when looping through an array (when the pointer will be the same always) use the same variable (in this case counter)要记住的主要事情是减少重复自己的次数,当循环数组时(当指针始终相同时)使用相同的变量(在这种情况下是计数器)

Your code is basically fine as far as timing goes - with intervals as long as 6 seconds you aren't going to notice if one timeout happens a microsecond after the other.就时间而言,您的代码基本上没问题 - 间隔长达 6 秒,您不会注意到一个超时是否发生在一微秒之后。

Your problem is a straightforward bug.你的问题是一个简单的错误。 There is a repetition of text[1] so the MSG2 never gets shown.有重复的 text[1],所以 MSG2 永远不会显示。

This is your snippet with just that change made and it works perfectly.这是您所做的更改的片段,并且效果很好。

 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"> <style> img { height: 500px; width: 450px; } h1 { color: darkgreen; margin-top: 20px; font-family: Comic Sans MS, cursive, sans-serif; } .button { margin-left: 45%; } </style> <script> function changeImage() { var img = document.getElementById("img"); img.src = images[x]; x++; if (x >= images.length) { x = 0; } setTimeout("changeImage()", 6000); } function changeText() { var txt = document.getElementById("message"); txt.textContent = text[y]; y++; if (y >= text.length) { y = 0; } setTimeout("changeText()", 6000); } var text = [], y = 0; text[0] = "MSG1"; text[1] = "MSG2"; text[2] = "MSG3"; setTimeout("changeText()", 6000); var images = [], x = 0; images[0] = "image1.jpg"; images[1] = "image2.jpg"; images[2] = "image3.jpg"; setTimeout("changeImage()", 6000); </script> </head> <body> <div class="container"> <div class="row"> <div class="col-md-3"></div> <div class="col-md-6"> <h1 id="message"> Hello </h1> <img id="img" src="image1.jpg"> </div> <div class="col-md-3"></div> </div> </div> </body> </html>

However, you mention efficiency, and again at such long time intervals it probably isn't going to make a great deal of difference as the JS is only called every 6 seconds but if you want to make more efficient code then consider ditching JS and using CSS animations instead - the browser will have a chance of using the GPU then.但是,您提到了效率,而且在如此长的时间间隔内,它可能不会产生很大的不同,因为 JS 仅每 6 秒调用一次,但是如果您想编写更高效的代码,请考虑放弃 JS 并使用而是使用 CSS 动画——然后浏览器将有机会使用 GPU。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM