无法控制台.log() .style.显示信息



当我点击输入标签时,我能够在显示和隐藏的下拉菜单之间正确切换,但是当控制台记录显示的样式时,我在控制台上什么也没有显示。无法看到这一点的解释是什么,我该如何去尝试正确地看到我使用的显示样式?

document.getElementById('search').addEventListener("click", function () {
const grid1 = document.querySelector(".modal");
grid1.style.display = grid1.style.display ? "none" : "flex";
console.log(grid1.style.display);
});

不使用' youelement .style. '使用getComputedStyle函数来获取任何属性的值,在本例中是"display",这是因为Computed style包含了元素的所有CSS属性。即使不为元素设置属性。您仍然可以在计算样式中找到该属性。

使用'getComputerStyle'修改代码

document.getElementById('search').addEventListener("click", function () {
const grid1=document.querySelector(".modal")
console.log(window.getComputedStyle(grid1).display)
grid1.style.display = window.getComputedStyle(grid1).display == "none" ? "flex" : "none";
console.log(window.getComputedStyle(grid1).display)
})
.modal {
display: none;
}
<input id="search">
<select class="modal"></select>

查看MDN Web文档

中的Window.getComputedStyle()

最新更新