如何使元素的可见度.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;
}
其他回答
这里有一个永久有条件的表达式 来检查元素的状态 然后切换它:
$('someElement').on('click', function(){ $('elementToToggle').is(':visible') ? $('elementToToggle').hide('slow') : $('elementToToggle').show('slow'); });
简单检查display
属性(或)visibility
取决于您喜欢何种隐形。例如:
if ($('#invisible').css('display') == 'none') {
// This means the HTML element with ID 'invisible' has its 'display' attribute set to 'none'
}
因为Elements with visibility: hidden or opacity: 0 are considered visible, since they still consume space in the layout
(截至2004年12月1日jj 查询: 可见选择器- 我们可以检查元素是否真的以这种方式可见:
function isElementReallyHidden (el) {
return $(el).is(":hidden") || $(el).css("visibility") == "hidden" || $(el).css('opacity') == 0;
}
var booElementReallyShowed = !isElementReallyHidden(someEl);
$(someEl).parents().each(function () {
if (isElementReallyHidden(this)) {
booElementReallyShowed = false;
}
});
if ( $(element).css('display') == 'none' || $(element).css("visibility") == "hidden"){
// 'element' is hidden
}
上述方法不考虑父母亲的可见度。为了也考虑父母的可见度,您应该使用.is(":hidden")
或.is(":visible")
.
例如,
<div id="div1" style="display:none">
<div id="div2" style="display:block">Div2</div>
</div>
上述方法将考虑
div2
可见时可见:visible
。但是,在很多情况下,特别是当您需要找到隐藏的父(母)是否发现任何错误时,上述情况也许有用,因为在这种情况下,隐藏的母(母)之间是否有错误。:visible
不会工作。
您可以在显示时添加一个类。添加一个类,show
。然后检查它有一个类:
$('#elementId').hasClass('show');
如果有的话它返回为真show
类。
添加像这样的 CSS :
.show{ display: block; }