如何解决如何将动态href添加到幻灯片设置背景图像数据的香草滑块?
我今天构建了一个自定义的原版图像滑块,后来意识到每张幻灯片都应该能够链接到不同的页面。我尝试将每个链接添加为数据属性(我以为我正在编码反应一秒钟并将其视为道具......哎呀)但随后链接被推入 slideArray
并打破了轮播试图将它(href)设置为背景图像。对我来说,在不必重新编码整个滑块的情况下为每张幻灯片添加自定义链接(无论是可访问性还是便利性)的最佳方法是什么?此滑块目前运行良好&& 响应迅速,所以我不想重做整个事情。
<div class="slider">
<div class="slide" data-background="https://picsum.photos/825/400"></div>
<div class="slide" data-background="https://picsum.photos/800/400"></div>
<div class="slide" data-background="https://picsum.photos/850/400"></div>
<div class="slide" data-background="https://picsum.photos/900/450"></div>
<a id="prev" class="control prev"></a>
<a id="next" class="control next"></a>
</div>
<a class="link">
</a>
<div class="slider"><a class="link">
<div class="slide" data-background="https://picsum.photos/825/400"></div>
<div class="slide" data-background="https://picsum.photos/800/400"></div>
<div class="slide" data-background="https://picsum.photos/850/400"></div>
<div class="slide" data-background="https://picsum.photos/900/450"></div>
</a><a id="prev" class="control prev"></a>
<a id="next" class="control next"></a>
</div>
<script>
const next = document.querySelector("#next");
const prev = document.querySelector("#prev");
const slideArray = [];
for (let i = 0; i < document.querySelectorAll('.slider div').length; i++) {
slideArray.push(document.querySelectorAll('.slider div')[i].dataset.background); //fill slide array with slider div nodes
}
console.log(slideArray)
let currentSlideIndex = -1;
function advanceSliderItem() {
currentSlideIndex++;
if (currentSlideIndex >= slideArray.length) {
currentSlideIndex = 0;
}
document.querySelector('.slider').style.csstext = 'background: url("' + slideArray[currentSlideIndex] + '") no-repeat center center; background-size: cover;';
}
function prevIoUsSliderItem() {
currentSlideIndex--;
if (currentSlideIndex <= -1) {
currentSlideIndex = slideArray.length - 1;
}
document.querySelector('.slider').style.csstext = 'background: url("' + slideArray[currentSlideIndex] + '") no-repeat center center; background-size: cover;';
}
next.addEventListener("click",advanceSliderItem )
prev.addEventListener("click",prevIoUsSliderItem )
let intervalID = setInterval(advanceSliderItem,5000);
advanceSliderItem()
</script>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。