我最近添加了两个横幅到我的网站,我想每 5 秒更改一次横幅, 不幸的是,它只显示第一个并卡住
这是我的 foreach 数据的完整代码
var links = ["http://site", "http://site"];
var images = ["/uploads/ad1.png", "/uploads/ad2.png"];
var i = 0;
var renew = setInterval(function() {
if (links.length == i) {
i = 0;
} else {
document.getElementById("bannerImage").src = images[i];
document.getElementById("bannerLink").href = links[i];
i++;
}
}, 500);
<?php foreach ($messages as $message){
?>
<a href="?id= <?php echo $message['message_id']?>" class="waves-effect waves-light"> details <i class="fas fa-angle-double-left ml-2"></i>
</div>
<br>
</div>
</div>
<div class="container">
<div class="text-center">
<a id="bannerLink" href="http://site" onclick="void window.open(this.href); return false;">
<img id="bannerImage" src="https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885__340.jpg" width="320" height="120" alt="some text">
</a>
</div>
</div>
</div>
最佳答案
这里的代码将每 5 秒更改一次图像和链接。
var links = ["http://site","http://site"];
var images = ["https://images.pexels.com/photos/414612/pexels-photo-414612.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500","https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885__340.jpg"];
var i = 0;
var renew = setInterval(function(){
document.getElementById("bannerImage").src = images[i];
document.getElementById("bannerLink").href = links[i];
i++;
if (i == links.length) {
i = 0;
}
}, 5000);
<div class="container">
<div class="text-center">
<a id="bannerLink" href="http://site" onclick="void window.open(this.href); return false;">
<img id="bannerImage" src="https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885__340.jpg" width="320" height="120" alt="some text">
</a>
</div>
</div>
我重新安排了循环,使其始终每 5 秒更改一次图像。在进行整轮重置之前,增加 5 秒。
我还将 500
更改为 5000
(以毫秒为单位)
关于javascript 横幅在第一个横幅上卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59793796/