我该如何使用纯JavaScript编写一个在JQuery中已经存在的切换函数?

7

昨天我试着使用JavaScript让这段代码工作了几个小时,因为我想尽可能地掌握基础知识,但最终放弃了并用JQuery编写。希望能得到一些如何在纯JS中编写的建议。我只是试图使用一个按钮来显示隐藏的“div”,感觉应该很简单,只是我忽视了某些东西:

JQuery代码:

$('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>
</div>

我尝试了类似这样的东西:
function toggle(id){
    var div1 = document.getElementById(id);
    if (div1.style.display == 'none') {
        div1.style.display = 'block'
    } else {
        div1.style.display = 'none'
    }
}

我没有使用CSS的“hide”类。但它在页面加载时显示了div,然后通过按钮隐藏它,而我希望相反的情况发生。


使用 hide 类,切换 div1 的类列表。 - Andy
5个回答

13
如果我正确地理解了你的问题,你想切换一个类的状态,比如添加/删除,例如对于菜单。因此,当您点击元素A以显示元素B,然后再次点击元素A以隐藏元素B时,您可以像这样做:
const elementClicked = document.querySelector("#elementClicked");
const elementYouWantToShow = document.querySelector("#elementYouWantToShow");

elementClicked.addEventListener("click", ()=>{
  elementYouWantToShow.classList.toggle("theClassYouWantToToggleBetween");
});

希望这能澄清事情:)


1
这个完美地解决了!非常感谢。我知道一定是我忽略了某些非常简单的东西! - brianna124
1
很高兴能帮助到你 :) - Petar

4

document.addEventListener('DOMContentLoaded', () => {
  const button = document.querySelector('.button');
  const elementToToggle = document.getElementById('element');    

  button.addEventListener('mousedown', () => {
    elementToToggle.classList.toggle('hide');
  });
});
#element {
  height: 100px;
  width: 200px;
  margin-top: 15px;
  background: #ddd;
}

#element.hide {
  display: none;
}
<button class="button">Toggle</button>
<div id="element"></div>


2

hidden 属性 可以解决问题。

<div id="more-brian" hidden>
<p id="brian-para">Brian is a husband and father who is very passionate [...]</p>
</div>

以下是 JavaScript 函数的示例:

function toggle(id) {
    var div1 = document.getElementById(id);
    if(div1.hidden) {
        div1.hidden = false;
    } else {
        div1.hidden = true;
    }
}

1

我认为你要查找的属性是 "className"。请尝试这样做:

function toggle(id){
   var x = document.getElementById(id);
   if(x.className == "hide") x.className = "show";
   else x.className = "hide";
}

然后它在CSS中定义了两个类的可见性方面。

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接