如何使元素的可见度.hide()
, .show()
,或.toggle()
?
如果一个元素是visible
或hidden
?
如何使元素的可见度.hide()
, .show()
,或.toggle()
?
如果一个元素是visible
或hidden
?
当前回答
它返回时返回false
如果元素不可见。
function checkVisible(e) {
if (!(e instanceof Element)) throw Error('not an Element');
const elementStyle = getComputedStyle(e);
if (elementStyle.display === 'none' || elementStyle.visibility !== 'visible' || elementStyle.opacity < 0.1) return false;
if (e.offsetWidth + e.offsetHeight + e.getBoundingClientRect().height +
e.getBoundingClientRect().width === 0) {
return false;
}
const elemCenter = {
x: e.getBoundingClientRect().left + e.offsetWidth / 2,
y: e.getBoundingClientRect().top + e.offsetHeight / 2
};
if (elemCenter.x < 0 || elemCenter.y < 0) return false;
if (elemCenter.x > (document.documentElement.clientWidth || window.innerWidth)) return false;
if (elemCenter.y > (document.documentElement.clientHeight || window.innerHeight)) return false;
let pointContainer = document.elementFromPoint(elemCenter.x, elemCenter.y);
do {
if (pointContainer === e) return true;
} while (pointContainer = pointContainer.parentNode);
return false;
}
其他回答
您也可以使用 plain JavaScript 来做到这一点 :
function isRendered(domObj) {
if ((domObj.nodeType != 1) || (domObj == document.body)) {
return true;
}
if (domObj.currentStyle && domObj.currentStyle["display"] != "none" && domObj.currentStyle["visibility"] != "hidden") {
return isRendered(domObj.parentNode);
} else if (window.getComputedStyle) {
var cs = document.defaultView.getComputedStyle(domObj, null);
if (cs.getPropertyValue("display") != "none" && cs.getPropertyValue("visibility") != "hidden") {
return isRendered(domObj.parentNode);
}
}
return false;
}
注:
到处工作
嵌套元素的工程
CSS 和内嵌样式的工作
不需要框架
如果隐藏在类 - d - no 类中
if (!$('#ele').hasClass('d-none')) {
$('#ele').addClass('d-none'); //hide
}
下面的代码检查元素是否隐藏在 jQuery 中或可见
// You can also do this...
$("button").click(function(){
// show hide paragraph on button click
$("p").toggle("slow", function(){
// check paragraph once toggle effect is completed
if($("p").is(":visible")){
alert("The paragraph is visible.");
} else{
alert("The paragraph is hidden.");
}
});
});
isHidden = function(element){
return (element.style.display === "none");
};
if(isHidden($("element")) == true){
// Something
}
使用隐藏选择, 您可以匹配所有隐藏元素
$('element:hidden')
使用可见选择, 您可以匹配所有可见元素
$('element:visible')