1

干杯,我有一个图像显示的代码,每隔几秒钟就会改变一次,但我不知道如何调整每个图像的大小,或者如何使它们都一样。

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

提前致谢!

4

1 回答 1

1

可以用css来完成。将图像包裹在 中div,设置它的尺寸并决定如何显示图像。

如果要拉伸图像以适合div然后将图像的width和设置height为 100%

#img-box {
  width: 400px;
  height: 400px;
  border: 1px solid black;
 
}
#img-box img {
  max-width: 100%;
  max-height: 100%;
   
}
<!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] = "https://upload.wikimedia.org/wikipedia/commons/a/a9/Bristol_MMB_%C2%AB42_River_Avon.jpg";
    images[1] = "https://upload.wikimedia.org/wikipedia/commons/1/19/Finsternis_Natur.jpg";
    images[2] = "https://upload.wikimedia.org/wikipedia/commons/8/8c/Black_CL.png";
  </script>
</head>

<body onload="startTimer()">
  <div id="img-box">
    <img id="img" src="https://upload.wikimedia.org/wikipedia/commons/0/03/Electricsheep-29142.jpg" />
  </div>
  <button type="button" onclick="displayPreviousImage()">Previous</button>
  <button type="button" onclick="displayNextImage()">Next</button>
</body>

</html>

于 2016-04-09T20:03:15.143 回答