我试图在按钮内仅使用JavaScript(没有jQuery和Bootstrap)。
如何通过单击带有纯JS和CSS的矩形按钮来创建类似轮播的效果?
我正在使用以下轮播代码:
.carousel-inner {
height: 200px;
background: black;
color: #fff;
}
<link rel="stylesheet" href="https://cdn.rawgit.com/twbs/bootstrap/v4-dev/dist/css/bootstrap.css">
<div id="carousel-example-generic" class="carousel slide" data-ride="carousel">
<ol class="carousel-indicators">
<li data-target="#carousel-example-generic" data-slide-to="0" class="active"></li>
<li data-target="#carousel-example-generic" data-slide-to="1"></li>
<li data-target="#carousel-example-generic" data-slide-to="2"></li>
</ol>
<div class="carousel-inner" role="listbox">
<div class="carousel-item active">
First
</div>
<div class="carousel-item">
Second
</div>
<div class="carousel-item">
Third
</div>
</div>
<a class="left carousel-control" href="#carousel-example-generic" role="button" data-slide="prev">
<span class="icon-prev" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="right carousel-control" href="#carousel-example-generic" role="button" data-slide="next">
<span class="icon-next" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://cdn.rawgit.com/twbs/bootstrap/v4-dev/dist/js/bootstrap.js"></script>
答案 0 :(得分:0)
您需要了解HTMLElements。您可以在Web检查器控制台中键入document.body
,然后深入研究对象,以浏览它们。它们具有很多功能,您不需要一无所知,但是如果您要使用vanilla js,那就太好了!
您需要了解的大事是childNodes
,eventListeners和offsetLeft
。
遵循这些原则(未经测试)应该可以帮助您达到目标。
const byId = (id) => document.getElementById(id);
const buttonContainer = byId("ButtonContainer");
const imageContainer = byId("ImageContainer");
let lastSelectedButton;
Array.from(buttonContainer.childNodes).forEach((child, childIndex) => {
child.addEventListener("click", () => {
if (lastSelectedButton) {
lastSelectedButton.classList.remove("selected");
}
const scrollToMe = imageContainer.childNodes[childIndex];
imageContainer.scrollX = scrollToMe.offsetLeft;
child.classList.add("selected");
lastSelectedButton = child;
});
});
如果您真的想添加香料,请添加一些Scroll Snapping。
如果您根本不想制作滚动版本而只想退出,请使用child.remove()
和element.appendChild(child)
。