切换当前元素的可见性 [英] Toggle visibility of the current element
本文介绍了切换当前元素的可见性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试编写一个函数 toggle_active
以在单击时显示隐藏的内容,并在再次单击时再次折叠内容.可悲的是,它不起作用.你能帮我修改一下吗?
I'm trying to write a function toggle_active
to show the hidden content on a click, and collapse the content again on one more click. Sadly, it does not work. Could you help me modify it?
function toggle_active(this){
var x = this.nextSibling;
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
};
}
.daccord_b{
display:none;
}
<header class="ca_h" onclick="toggle_active(this);">
<i class="i i-plus ca_hi"></i>
Title
</header>
<div class="had daccord_b">Hidden content</div>
推荐答案
使用方法 nextElementSibling
返回下一个元素.并且没有必要使用 if {}
运算符.
Use method nextElementSibling
to return the next element. And it is not necessary to use the if {}
operator.
不要将 this
用于函数中的参数.
Don't use this
for arguments in functions.
您的任务更正确的方法是方法 toggle()
,您的类在 css .daccord_b
中使用该方法.
The more correct way for your task is method toggle()
, which your class uses in css .daccord_b
.
function toggle_active(el) {
var x = el.nextElementSibling;
x.classList.toggle("daccord_b");
}
.daccord_b {
display: none;
}
<header class="ca_h" onclick="toggle_active(this);">
<i class="i i-plus ca_hi"></i>
Title
</header>
<div class="had daccord_b">Hidden content</div>
使用 style.display
的第二种解决方案.
Second solution using style.display
.
function toggle_active(el) {
var x = el.nextElementSibling;
x.style.display = x.style.display === 'block' ? 'none' : 'block';
}
.daccord_b {
display: none;
}
<header class="ca_h" onclick="toggle_active(this);">
<i class="i i-plus ca_hi"></i>
Title
</header>
<div class="had daccord_b">Hidden content</div>
这篇关于切换当前元素的可见性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文