如何将动态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 (将#修改为@)