Javascript classList.添加到高度为0px的元素



不确定我是否在这里错过了一些明显的东西,但我正试图将一个类添加到具有0px高度的元素中。

const teamMemberBioShow = function() {
const bio = document.querySelector(".bio");
if (bio.classList.contains("hidden")) {
bio.classList.remove("hidden");
bio.classList.add("show");
} else {
bio.classList.remove("show");
bio.classList.add("hidden");
}
}
const teamMemberBioMore = document.querySelector(".bio-more");
teamMemberBioMore.addEventListener('click', teamMemberBioShow);
.bio.hidden {
opacity: 0;
height: 0;
}
.bio.show {
opacity: 1;
height: auto;
}
<div class="bio hidden">
Bio goes here
</div>
<div class="bio-more">Read Bio</div>

单击,添加.show类,删除.hidden类。但是,如果.hidden类将0px分配给它,则不起作用。

问题是,如果你把高度0,但不设置overflow: hidden的文本内容,该div将溢出并覆盖可点击的文本,所以点击事件不会被调度:

const teamMemberBioShow = function() {
const bio = document.querySelector(".bio");
if (bio.classList.contains("hidden")) {
bio.classList.remove("hidden");
bio.classList.add("show");
} else {
bio.classList.remove("show");
bio.classList.add("hidden");
}
}
const teamMemberBioMore = document.querySelector(".bio-more");
teamMemberBioMore.addEventListener('click', teamMemberBioShow);
.bio.hidden {
opacity: 0;
height: 0;
overflow: hidden;
}
.bio.show {
opacity: 1;
height: auto;
}
<div class="bio hidden">
Bio goes here
</div>
<div class="bio-more">Read Bio</div>

这是因为即使你的元素。Hidden的不透明度为0,它会与click事件混淆,并且会溢出到其他div。

如果你想隐藏一个元素

试着把display: none

最新更新