gpt4 book ai didi

Javascript 数组导航

转载 作者:行者123 更新时间:2023-12-03 02:45:05 25 4
gpt4 key购买 nike

我正在尝试使用数组数据创建一个改变 div 背景的导航。

它没有像我想要的那样工作。

我尝试在 addEventListener 中使用 if 和“click”功能。

  
var designNextBg = document.getElementById('js-nextbg');
var designBg = document.getElementById('js-designBg');
var designBgArray = [
'url(images/ipb.png)',
'url(images/ipg.png)',
'url(images/ipr.png)',
'url(images/ipw.png)',
'url(images/ipy.png)'
];
var positionBg = document.getElementById('js-positionBg');
var i = 0;

designNextBg.addEventListener('click', function(e) {
if (i = 0) {
designBg.style.backgroundImage = designBgArray[i];
i = i + 1;
positionBg.innerHTML = "0" + (i + 1) + "/05";
return i;
} else if (i = 4) {
designBg.style.backgroundImage = designBgArray[i];
i = 0;
positionBg.innerHTML = "0" + (i + 1) + "/05";
return i;
} else {
designBg.style.backgroundImage = designBgArray[i];
i = i + 1;
positionBg.innerHTML = "0" + (i + 1) + "/05";
return i;
};
});
<div id="js-designBg" class="design-bg">
<div class="design-navigation">
<span id="js-positionBg">01/05</span>
<p>
<a id="js-prevbg" class="angle-buttons"><i class="fa fa-angle-left"></i></a>
<a id="js-nextbg" class="angle-buttons"><i class="fa fa-angle-right"></i></a>
</p>
</div>
</div>

最佳答案

你的代码太复杂了。我添加了两种方法来处理 i 并将其保持在边界内。这一次,您可以在点击处理程序(当前已注释掉)中执行此操作,或者您可以在那里连续递增/递减并使用 oneliner 计算数组内的实际索引。

var designBg = document.getElementById('js-designBg');
var designBgArray = [
'url(images/ipb.png)',
'url(images/ipg.png)',
'url(images/ipr.png)',
'url(images/ipw.png)',
'url(images/ipy.png)'
];
var positionBg = document.getElementById('js-positionBg');
var i = 0;

var nextButton = document.getElementById('js-nextbg');
var prevButton = document.getElementById('js-prevbg');

nextButton.addEventListener('click', function(e) {
//if(++i === designBgArray.length) i=0;
++i;
updateView();
});

prevButton.addEventListener('click', function(e) {
//if(--i < 0) i += designBgArray.length;
--i;
updateView();
});


function lz(nr){//a simple leading zero function
return String(nr).padStart(2, 0);
}

funciton updateView(){
var len = designBgArray.length;
//get i back into the boundaries
//you could also take care of that in the click-handler
//but this way, it's all in one place
var index = i%len + (i<0? len: 0);

designBg.style.backgroundImage = designBgArray[index];
positionBg.textContent = lz(index+1) + "/" + lz(len);
}
<div id="js-designBg" class="design-bg">
<div class="design-navigation">
<span id="js-positionBg">01/05</span>
<p>
<a id="js-prevbg" class="angle-buttons"><i class="fa fa-angle-left"></i></a>
<a id="js-nextbg" class="angle-buttons"><i class="fa fa-angle-right"></i></a>
</p>
</div>
</div>

关于Javascript 数组导航,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48136174/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com