如何在不使用 ID ans .getElemetByID 方法的情况下为我的按钮制作一个只在该按钮所在的 block 上工作的脚本? 这是一个示例,其中我使用 ID 且仅用于一个按钮,但我想让所有按钮展开它们的父 block 。
function toggle() {
var tBlock = document.getElementById("textblock");
var tText = document.getElementById("text");
if (tBlock.style.height === "100px" && tText.style.height === "60px") {
tBlock.style.height = "auto";
tText.style.height = "auto";
} else {
tBlock.style.height = "100px";
tText.style.height = "60px";
}
}
.docText {
height: 100px;
width: 100px;
background: green;
margin-bottom: 5px;
}
.docTextContent {
height: 60px;
width: 100px;
overflow: hidden;
}
<div class="docText" id="textblock">
<div class="docTextContent" id="text">
TextTextText
TextTextText
TextTextText
TextTextText
TextTextText
TextTextText
</div>
<button class="toggle_btn" onclick="toggle()">Show</button>
</div>
<div class="docText">
<div class="docTextContent">
TextTextText
TextTextText
TextTextText
TextTextText
TextTextText
TextTextText
</div>
<button class="toggle_btn">Show</button>
</div>
<div class="docText">
<div class="docTextContent">
TextTextText
TextTextText
TextTextText
TextTextText
TextTextText
TextTextText
</div>
<button class="toggle_btn">Show</button>
</div>
最佳答案
您可以通过类名检索所有切换按钮,然后在绑定(bind)点击处理程序时循环遍历它们来完成此操作。这是一个工作示例:
// GET ALL TOGGLES
var toggles = document.getElementsByClassName("toggle_btn");
// LOOP THROUGH EACH TOGGLE AND APPLY AN EVENT LISTENER
for (var i = 0; i < toggles.length; i++) {
toggles[i].addEventListener("click", function(e) {
e.preventDefault();
// GET .docTextContent ELEMENT
var tBlock = this.parentElement.children[0];
// IF .docTextContent IS "CLOSED"
if (tBlock.style.height === "60px" || tBlock.style.height === "") {
tBlock.style.height = "auto";
}
// .docTextContent IS "OPEN"
else {
tBlock.style.height = "60px";
}
});
}
.docText {
width: 100px;
background: green;
margin-bottom: 5px;
}
.docTextContent {
height: 60px;
width: 100px;
overflow: hidden;
}
<div class="docText" id="textblock">
<div class="docTextContent" id="text">
TextTextText TextTextText TextTextText TextTextText TextTextText TextTextText
</div>
<button class="toggle_btn">Show</button>
</div>
<div class="docText">
<div class="docTextContent">
TextTextText TextTextText TextTextText TextTextText TextTextText TextTextText
</div>
<button class="toggle_btn">Show</button>
</div>
<div class="docText">
<div class="docTextContent">
TextTextText TextTextText TextTextText TextTextText TextTextText TextTextText
</div>
<button class="toggle_btn">Show</button>
</div>
关于javascript - 不使用唯一 ID 影响所选 div 的按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49587799/