我需要帮助来整理这段代码,目标是加载的每个页面显示3秒钟的阵列图像。
第一页工作正常。问题在于,在第一个页面加载后,每个页面的图像更改速度都会更快。
<div data-role="page" id="page1" class="banners">
<div data-role="main" class="ui-content">
<div class="patrocinadores" align="center">
<img src="" width="100%" class="bannerPatrocinador">
</div>
</div>
</div>
<div data-role="page" id="page2" class="banners">
<div data-role="main" class="ui-content">
<div class="patrocinadores" align="center">
<img src="" width="100%" class="bannerPatrocinador">
</div>
</div>
</div>
<div data-role="page" id="page3" class="banners">
<div data-role="main" class="ui-content">
<div class="patrocinadores" align="center">
<img src="" width="100%" class="bannerPatrocinador">
</div>
</div>
</div>
<script>
$('.banners').on("pagecreate",function(event){
clearInterval(trocarImagem);
let cmpBanner1 = localStorage.getItem("cmpBanner1");
let cmpBanner2 = localStorage.getItem("cmpBanner2");
let cmpBanner3 = localStorage.getItem("cmpBanner3");
let cmpLink1 = localStorage.getItem("cmpLink1");
let cmpLink2 = localStorage.getItem("cmpLink2");
let cmpLink3 = localStorage.getItem("cmpLink3");
let imagens = ["adm/img/mkt/"+cmpBanner1, "adm/img/mkt/"+cmpBanner2+"", "adm/img/mkt/"+cmpBanner3+""];
let imagemAtual = 0;
function trocarImagem(){
imagemAtual = (imagemAtual + 1) % 3;
var teste = $('.bannerPatrocinador').attr('src',imagens[imagemAtual]);
}
setInterval(trocarImagem, 3000);
});
</script>
答案 0 :(得分:1)
您的代码中存在几个问题:
工作示例:http://jsfiddle.net/ws5p6nbk/
var interval;
var imagemAtual = 0;
function trocarImagem() {
var imagens = ["https://s3.amazonaws.com/wmfeimages/wp-content/uploads/2018/09/27182802/4189366235_060e3e8e6f_z.jpg", "https://media.mnn.com/assets/images/2019/02/lexi.JPG.653x0_q80_crop-smart.jpg", "https://assets3.thrillist.com/v1/image/2709211/size/tmg-article_tall.jpg"];
console.log(imagemAtual);
imagemAtual = (imagemAtual + 1) % 3;
var activePage = $.mobile.activePage;
activePage.find('.bannerPatrocinador').attr('src', imagens[imagemAtual]);
}
$(document).on("pagecreate", '.banners', function(event) {
clearInterval(interval);
interval = setInterval(trocarImagem, 3000);
});
请测试这些更改,如果满意,请接受答案。