【发布时间】:2022-12-08 00:55:22
【问题描述】:
如何检测元素是否可见?
我的 HTML 原样: `
<a onclick="showTestElement()">Show</a>
<a onclick="hideTestElement()">Hide</a>
`
【问题讨论】:
-
这完全取决于它是如何被隐藏的,这在你的问题中并不清楚。
标签: javascript html jquery css
如何检测元素是否可见?
我的 HTML 原样: `
<a onclick="showTestElement()">Show</a>
<a onclick="hideTestElement()">Hide</a>
`
【问题讨论】:
标签: javascript html jquery css
当一个元素被 display:none 隐藏时,该元素将不会占用任何空间。 查明一个元素是否被隐藏并具有可见性:hidden
【讨论】:
这取决于你如何隐藏/显示你的元素。
使用display: none;
const test = document.getElementById("test");
function showTestElement() {
test.style.visibility = "visible";
}
function hideTestElement() {
test.style.visibility = "hidden";
}
div#test {
width: 100px;
height: 100px;
background: lightcoral;
}
<button onclick="showTestElement()">Show</button>
<button onclick="hideTestElement()">Hide</button>
<div id="test"></div>
使用visibility: hidden;
const test = document.getElementById("test");
function showTestElement() {
test.style.display = "block"; // or whatever default display the element has
}
function hideTestElement() {
test.style.display = "none";
}
div#test {
width: 100px;
height: 100px;
background: lightcoral;
}
<button onclick="showTestElement()">Show</button>
<button onclick="hideTestElement()">Hide</button>
<div id="test"></div>
使用opacity: 0;
const test = document.getElementById("test");
function showTestElement() {
test.style.opacity = 1;
}
function hideTestElement() {
test.style.opacity = 0;
}
div#test {
width: 100px;
height: 100px;
background: lightcoral;
}
<button onclick="showTestElement()">Show</button>
<button onclick="hideTestElement()">Hide</button>
<div id="test"></div>
所有这三个都做不同的事情。 display: none; 从文档流中完全删除该元素。 visibility: none; 隐藏元素(但它仍然存在于文档流中)但禁用所有指针事件。 opacity: 0; 只是隐藏了元素。
【讨论】: