【问题标题】:hyperlinking an image in an array from another array从另一个数组超链接数组中的图像
【发布时间】:2019-09-22 00:47:24
【问题描述】:

我有 2 个数组,我有图像,另一个有链接。 使用设置间隔,我以 2000 毫秒更改图像。 如何使用链接超链接图像。

var img_array = <?php echo json_encode($images); ?>;
var link_array = <?php echo json_encode($links); ?>;
    var image = document.getElementById("aaa");
    var index=0;
function slide(){
    document["aaa"].src = img_array[index];
    index++;
    if(index>=img_array.length)
    {
    index=0;
    }
}
setInterval("slide()",2000);
    </script>

【问题讨论】:

  • 如果你想让 作为链接可点击,它必须在 标签内

标签: javascript php arrays


【解决方案1】:

这是一个例子。它并不完美,因为如果您第一次看到它,则图像没有加载。这就是为什么大多数网站会生成所有带有链接的图像,然后只是隐藏和显示它们。

var img_array = ["https://images.pexels.com/photos/853168/pexels-photo-853168.jpeg", "https://images.pexels.com/photos/46710/pexels-photo-46710.jpeg", "https://images.unsplash.com/photo-1529736576495-1ed4a29ca7e1"];
var link_array = ["index1.html","index2.html","index3.html"];
var image = document.getElementById("image");
var link = document.getElementById("link");
// The first (which is the 0) is already loaded, so we need to skip it from here.
var index = 1;

function slide(){
    image.src = img_array[index];
    link.href = link_array[index];
    index++;
    
    if(index >= img_array.length) {
      index=0;
    }
}

setInterval(slide, 2000);
&lt;a href="index1.html" id="link"&gt;&lt;img src="https://images.pexels.com/photos/853168/pexels-photo-853168.jpeg" id="image" width="200"&gt;&lt;/a&gt;

或者,如果您无法更改 DOM,或者您想隐藏 url,您可以执行以下操作:

var img_array = ["https://images.pexels.com/photos/853168/pexels-photo-853168.jpeg", "https://images.pexels.com/photos/46710/pexels-photo-46710.jpeg", "https://images.unsplash.com/photo-1529736576495-1ed4a29ca7e1"];
var link_array = ["index1.html","index2.html","index3.html"];
var image = document.getElementById("image");
// The first (which is the 0) is already loaded, so we need to skip it from here.
var index = 1;

function slide(){
    image.src = img_array[index];
    index++;
    
    if(index >= img_array.length) {
      index=0;
    }
}

image.addEventListener("click", function() {
    // This is because of the sandbox environment.
    console.log(link_array[index]);
    // This is what you need.
    window.open(link_array[index]);
});

setInterval(slide, 2000);
.pointer {
  cursor: pointer;
}
&lt;img src="https://images.pexels.com/photos/853168/pexels-photo-853168.jpeg" id="image" class="pointer" width="200"&gt;

但是在这种情况下,您可能会被浏览器阻止,或者如果在加载新图像后注册了点击,则可能会导致点击失败。

【讨论】:

    猜你喜欢
    • 2021-10-12
    • 2022-12-31
    • 2017-09-03
    • 2012-05-23
    • 2022-07-06
    • 2015-06-23
    • 1970-01-01
    • 1970-01-01
    • 2016-10-22
    相关资源
    最近更新 更多