我有2个数组,我带有图像,另一个带有链接。 使用设置的间隔,我将图像更改为2000millisec。 如何通过链接使图像超链接。
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>
答案 0 :(得分:0)
这是一个例子。这不是完美的,因为如果您是第一次看到它,则不会加载图像。这就是为什么大多数网站都生成带有链接的所有图像,然后隐藏并显示它们的原因。
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);
<a href="index1.html" id="link"><img src="https://images.pexels.com/photos/853168/pexels-photo-853168.jpeg" id="image" width="200"></a>
或者,如果您无法更改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;
}
<img src="https://images.pexels.com/photos/853168/pexels-photo-853168.jpeg" id="image" class="pointer" width="200">
但是,在这种情况下,您可能会被浏览器阻止,或者如果在加载新图像后注册了点击,则可能会产生误点击。