如何使元素的可见度.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;
}
其他回答
就是这样jj 查询内部解决这个问题 :
jQuery.expr.pseudos.visible = function( elem ) {
return !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length );
};
如果您不使用 jQuery, 您可以使用这个代码, 并将其转换为您自己的功能 :
function isVisible(elem) {
return !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length );
};
哪个isVisible
将返回true
只要元素是可见的。
if($('#postcode_div').is(':visible')) {
if($('#postcode_text').val()=='') {
$('#spanPost').text('\u00a0');
} else {
$('#spanPost').text($('#postcode_text').val());
}
$('#clickme').click(function() {
$('#book').toggle('slow', function() {
// Animation complete.
alert($('#book').is(":visible")); //<--- TRUE if Visible False if Hidden
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="clickme">
Click here
</div>
<img id="book" src="https://upload.wikimedia.org/wikipedia/commons/8/87/Google_Chrome_icon_%282011%29.png" alt="" width="300"/>
来源(来自我的博客):
您需要同时检查 显示和可见度 :
if ($(this).css("display") == "none" || $(this).css("visibility") == "hidden") {
// The element is not visible
} else {
// The element is visible
}
如果我们检查$(this).is(":visible")
,j 查询自动检查这两个东西。