bri*_*124 3 javascript jquery toggle show-hide
昨天试图让这段代码使用 JavaScript 工作几个小时,因为我真的很想尽可能地了解基础知识,但最终放弃并用 JQuery 编写它。想要一些关于如何用 vanilla JS 编写的建议。我只是想用一个按钮来显示一个隐藏的“div”,所以我觉得它应该很简单,我只是忽略了一些东西:
查询:
$('document').ready(function() {
$('.aboutBtn').click(function() {
$('#more-brian').toggleClass('hide');
});
})
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
我试过这样的事情:
function toggle(id){
var div1 = document.getElementById(id);
if (div1.style.display == 'none') {
div1.style.display = 'block'
} else {
div1.style.display = 'none'
}
}
Run Code Online (Sandbox Code Playgroud)
我没有在 CSS 'hide' 类中使用它。但它在页面加载时显示 div,然后用按钮隐藏它,我希望相反的情况发生。
如果我正确理解您的问题,您希望在活动和非活动类之间切换,例如添加/删除它,例如菜单。因此,当您单击元素 A 以显示元素 B,然后再次单击元素 A 以隐藏元素 B 时,您可以这样做:
const elementClicked = document.querySelector("#elementClicked");
const elementYouWantToShow = document.querySelector("#elementYouWantToShow");
elementClicked.addEventListener("click", ()=>{
elementYouWantToShow.classList.toggle("theClassYouWantToToggleBetween");
});
Run Code Online (Sandbox Code Playgroud)
希望这可以解决问题:)
| 归档时间: |
|
| 查看次数: |
7697 次 |
| 最近记录: |