gpt4 book ai didi

javascript - 将类事件设置为下一个幻灯片元素

转载 作者:行者123 更新时间:2023-11-28 05:30:35 26 4
gpt4 key购买 nike

我有一个关于 Javascript 的问题。您可以在下面找到我的 HTML 标记

<div class="slides">
<div class="slide active" id="one"></div>
<div class="slide" id="two"></div>
<div class="slide" id="third"></div>
<div class="slide" id="fourth"></div>
</div>

<button onclick="slide-down()">
Next slide
</button>

<button onclick="slide-up()">
Previous slide
</button>

如果用户单击按钮向下滑动以使用纯 JavaScript 删除“active”类并将其设置为下一个幻灯片元素,我该怎么办?

最佳答案

可以使用单个函数,设置class<button>元素到"prev""next" ,通过点击button .className发挥作用; .getElementsByClassName() , .nextElementSibling , .previousElementSibling

.active {
color: green;
}
<div class="slides">
<div class="slide active" id="one">one</div>
<div class="slide" id="two">two</div>
<div class="slide" id="third">third</div>
<div class="slide" id="fourth">fourth</div>
</div>

<button class="next" onclick="slide(this.className)">
Next slide
</button>

<button class="prev" onclick="slide(this.className)">
Previous slide
</button>
<script>
var active = document.getElementsByClassName("active");

function slide(prevNext) {
if (prevNext === "next") {
if (active[0].nextElementSibling) {
active[0].nextElementSibling.className = "active";
active[0].className = "";
}
} else {
if (active[0].previousElementSibling) {
active[0].previousElementSibling.className = "active";
active[active.length - 1].className = "";
}
}
}
</script>

关于javascript - 将类事件设置为下一个幻灯片元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39730980/

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