使用原生 JavaScript 隐藏 div 的动态方法

问题描述 投票:0回答:4
javascript html css string object
4个回答
16
投票

使用

this

<div class="setup" onclick="show(this)">

JavaScript:

function show(elem) {
    var paragraph = elem.querySelector(".hidden");
    if (paragraph.style.display == "none") {
        paragraph.style.display = "block";
    } else {
        paragraph.style.display = "none";
}

希望这有帮助!


2
投票

是的,有办法!

您可以获取所有元素,通过

forEach
迭代它们,并将您的函数分配给它们的
onclick
属性:

document.querySelectorAll('.setup').forEach(div => {
    div.onclick = showElem;
});

这样做,您可以去掉 HTML 元素上的

onlick


要获取它们的子元素(显然是您想要隐藏/显示的子元素),您的

show()
函数可以如下所示:

function show() {
    const hidden = this.getElementsByClassName('hidden')[0];
    if (hidden.style.display == 'none') {
    hidden.style.display = 'block';
  } else {
    hidden.style.display = 'none';
  }
}

大家一起:

document.querySelectorAll('.setup').forEach(div => {
	div.onclick = show;
});

function show() {
	const hidden = this.getElementsByClassName('hidden')[0];
	if (hidden.style.display == 'none') {
  	hidden.style.display = 'block';
  } else {
  	hidden.style.display = 'none';
  }
}
.setup {
  border-top: solid #ccc 3px;
  border-bottom: solid #ccc 3px;
  margin-bottom: 5%;
}

.setup:hover {
    cursor: pointer;
}

.hidden {
  text-align: center;
  font-weight: bold;
  border-top: solid black 3px;
  border-bottom: solid black 3px;
  background-color: yellow;
  display: none;
}
<div class="setup">
Click to show
  <p class="hidden">
    I'm some stuff
  </p>
</div>

<div class="setup">
Click to show
  <p class="hidden">
    I'm more stuff
  </p>
</div>

JS 小提琴:http://jsfiddle.net/ba7yfmz6/38/


更多信息:

forEach

querySelectorAll()


2
投票

您可以使用

this

此外,由于

div
没有
style
属性,因此第一次单击时检查
style.display === 'none'
始终为 false;它将把
style.display
设置为 none。检查计算的样式将在第一次单击时显示隐藏元素。

function show(el) {
  const toggle = el.querySelector('.hidden');
  
  toggle.style.display = window.getComputedStyle(toggle).display === 'none' ? 'block' : 'none';
}
.setup {
  border-top: solid #ccc 3px;
  border-bottom: solid #ccc 3px;
  margin-bottom: 5%;
}

.setup:hover {
    cursor: pointer;
}

.hidden {
  text-align: center;
  font-weight: bold;
  border-top: solid black 3px;
  border-bottom: solid black 3px;
  background-color: yellow;
  display: none;
}
<div class="setup" onclick="show(this)">
Click to show
  <p class="hidden">
    I'm some stuff
  </p>
</div>

<div class="setup" onclick="show(this)">
Click to show
  <p class="hidden">
    I'm more stuff
  </p>
</div>


0
投票
<div class="setup" onclick="show(this)">

然后是 JavaScript:

function show(that) {   
    var hiddenElements = that.getElementsByClassName('hidden');
    for (var i = 0; i < hiddenElements.length; i++) {
        var style = hiddenElements[i].style;
        style.display = style.display == "block" ? "none" : "block";
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.