标题基于更改图像?

时间:2015-10-13 00:39:27

标签: javascript jquery html css image

我有这段代码:

<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() {  //this is started when the body is loaded
          setInterval(displayNextImage, 10000);
      }

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

基本上每10秒(由setInterval定义)它会变为下一个图像,然后再循环回第一个图像。 我需要的是,当显示图像0时,它会在图像“此图像是由其他人拍摄”下显示一个标题,但是当它变为第二个图像(图像1)时,它会将其更改为第二张图片的标题等等? 如果需要,最好使用Javascript或JQuery(我更擅长JavaScript)

我知道可以通过在Photoshop中编辑照片,在底部添加一些空格并添加一些文字来完成,但我觉得它看起来不太好。

1 个答案:

答案 0 :(得分:1)

您可以使用displayNextImage(),displayPreviousImage()函数将准备好的标题放入DIV元素中:

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

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

      function startTimer() {  //this is started when the body is loaded
          setInterval(displayNextImage, 10000);
      }

      var images = [], captions = [], x = -1;
      images[0] = "image0.jpg";
      images[1] = "image1.jpg";
      images[2] = "image2.jpg";
      images[3] = "image3.jpg";

      captions[0] = "foo";
      captions[1] = "bar";
      captions[2] = "foobar";
      captions[3] = "foobarfoo";
</script>

在您的HTML中,添加<div id="cap"></div>