我认为jQuery可以用.next()有效地完成这项工作,但我正在寻找一个学习香草的javascript解决方案。这是相关的块:
HTML
<div class="collapse-boxes-and-form-section">
<div class="collapse-boxes-column">
<h2 class="collapse-boxes-h2">Lorem Ipsum is simply dummy text</h2>
<a onClick="collapseboxtoggle()">
<div class="icon-collapse-box">
<img class="icon-collapse-icon" src="/assets/img/pageimg/image.png" width="70px">
<h4 class="icon-collapse-box-title">Lorem Ipsum is simply dummy text</h4>
<p class="icon-collapse-box-p" style="height:auto">Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.</p>
</div>
</a>
<a onClick="collapseboxtoggle()">
<div class="icon-collapse-box collasped-box">
<img class="icon-collapse-icon" src="/assets/img/pageimg/image.png" width="60px">
<h4 class="icon-collapse-box-title">Lorem Ipsum is simply dummy text</h4>
<p class="icon-collapse-box-p">Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.</p>
</div>
</a>
</div>
简而言之,当点击“.icon-collapse-box”类时,我试图展开并折叠“.icon-collapse-box-p”类中的单词。该函数似乎正在工作(虽然杂乱无章),但我需要它来扩展和折叠,具体取决于单击哪个特定的“.icon-collapse-box”而不为每个框添加唯一的类名并复制该函数。
JS
function collapseboxtoggle() {
var nav = document.querySelector(".icon-collapse-box-p");
if (nav.style.height === "auto") {
nav.style.height = "0px";
nav.style.gridRowStart = "2";
nav.style.opacity = "0";
nav.style.lineHeight = "0";
nav.style.marginTop = "-21px";
} else {
nav.style.height = "auto";
nav.style.gridRowStart = "2";
nav.style.opacity = "1";
nav.style.lineHeight = "2.0";
nav.style.marginTop = "0px";
}
}
以下是我认为可能有所帮助的一些事情,但未能成功实施(缺乏技术诀窍或其他原因):
除了jQuery之外还有什么帮助吗?
如果它有帮助,请使用此codepen: https://codepen.io/anon/pen/RMjXmJ
答案 0 :(得分:0)
首先,更新您的HTML部分。添加&#34;事件&#34;你的函数调用:
<a onClick="collapseboxtoggle(event)">
在Javascript上你可以使用该参数来获取点击的DOM元素,这样你就可以在这个DOM中搜索你的元素
function collapseboxtoggle(e) {
var box = e.currentTarget;
var nav = box.getElementsByClassName("icon-collapse-box-p")[0];
它可以更优雅,但现在它可以工作