可变href链接?计时器上的图像

时间:2017-04-21 22:06:34

标签: css image timer carousel var

您好我已经想出如何使用css在计时器上创建旋转图像轮播,但我不知道如何制作一个href变量。是否可以将不同的链接与每个图像相关联?提前谢谢!

<div class="sliderHolder columns-6 floatRight">

<div class="sliderButtonShadow"></div>
<a href="#"><img id="slider" src="image1.jpg" align="middle" class="sliderImage"></a>

 <script type = "text/javascript">

        var image=document.getElementById("slider");
        var currentPos = 0;
        var images = ["image1.jpg","image2.jpg", "image3.jpg"]

        function volgendefoto() {
            if (++currentPos >= images.length) currentPos = 0;
            image.src = images[currentPos];
        }

        setInterval(volgendefoto, 3000);

    </script>

1 个答案:

答案 0 :(得分:1)

添加指向页面的链接,为其指定ID,然后将数组转换为具有图片网址的对象以及与每个网址关联的链接,并在转换图片时更新链接的href。< / p>

var image = document.getElementById("slider");
var link = document.getElementById('sliderLink');
var currentPos = 0;
var images = [
  { 'img':"http://kenwheeler.github.io/slick/img/fonz1.png",
    'url':'http://image1.com'
  },
  { 'img':"https://s-media-cache-ak0.pinimg.com/originals/33/3b/4f/333b4f22ae39d1aaf8c23d77e759d8e1.jpg",
    'url':'http://image2.com'
  },
  { 'img':"http://www.star2.com/wp-content/uploads/2015/06/happy-days-770x470.jpg",
    'url':'http://image3.com'
  }
];

function volgendefoto() {
  if (++currentPos >= images.length) currentPos = 0;
  image.src = images[currentPos].img;
  link.href = images[currentPos].url;
}

setInterval(volgendefoto, 3000);
<a id="sliderLink" href="#"><img id="slider" src="http://www.star2.com/wp-content/uploads/2015/06/happy-days-770x470.jpg" align="middle" class="sliderImage"></a>