昨天我试图使用 JavaScript 让这段代码工作几个小时,因为我真的很想尽可能地掌握基础知识,但最终放弃并用 JQuery 编写了它。想要一些关于如何用 vanilla JS 编写的建议。我只是想用一个按钮来显示一个隐藏的“div”所以我觉得它应该很简单而且我只是忽略了一些东西:
查询:
$('document').ready(function() {
$('.aboutBtn').click(function() {
$('#more-brian').toggleClass('hide');
});
})
HTML:
<div class="row">
<div class="card col-sm-6">
<h5 class="card-title">Brian Davis</h5>
<img class="card-img-top" src="../soccer-travel-site/img/brian-davis.jpg" alt="Brian Davis photo">
<div class="card-body">
<p class="card-text">Brian is the founder of AO Adventures and an original host of the BarrelProof Podcast.<button type="button" class="btn btn-danger aboutBtn">More About Brian</button></p>
</div>
<div id="more-brian" class="hide">
<p id="brian-para">Brian is a husband and father who is very passionate about soccer. He has been to over 50 U.S. Men's and Women's National Team games all around the world. In his spare time he is a co-host of the BarrelProof Podcast.</p>
</div>
</div>
我试过这样的事情:
function toggle(id){
var div1 = document.getElementById(id);
if (div1.style.display == 'none') {
div1.style.display = 'block'
} else {
div1.style.display = 'none'
}
}
我没有将它与 CSS“隐藏”类一起使用。但它在页面加载时显示 div,然后用按钮隐藏它,我希望相反的事情发生。
原文由 brianna124 发布,翻译遵循 CC BY-SA 4.0 许可协议
如果我正确理解了您的问题,您希望在活动类和非活动类之间切换,例如添加/删除它,例如用于菜单。所以,当你点击元素A,显示元素B,然后再次点击元素A隐藏元素B,你可以这样做:
希望这能解决问题 :)