如何使元素的可见度.hide()
, .show()
,或.toggle()
?
如果一个元素是visible
或hidden
?
如何使元素的可见度.hide()
, .show()
,或.toggle()
?
如果一个元素是visible
或hidden
?
当前回答
expect($("#message_div").css("display")).toBe("none");
其他回答
它返回时返回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;
}
$(document).ready(function() {
var visible = $('#tElement').is(':visible');
if(visible) {
alert("visible");
// Code
}
else
{
alert("hidden");
}
});
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<input type="text" id="tElement" style="display:block;">Firstname</input>
通常当检查某物是否可见时, 您会立即直接去做其他事情。 jQuery 链条让事情变得容易。
所以,如果您有一个选择器, 并且只有显示或隐藏时才想要对它执行某些动作, 您可以使用filter(":visible")
或filter(":hidden")
然后用您想要采取的行动链绑住它。
所以,而不是一个if
语句, 像这样的语句 :
if ($('#btnUpdate').is(":visible"))
{
$('#btnUpdate').animate({ width: "toggle" }); // Hide button
}
或更有效率,但更丑陋:
var button = $('#btnUpdate');
if (button.is(":visible"))
{
button.animate({ width: "toggle" }); // Hide button
}
你可以单行完成所有任务:
$('#btnUpdate').filter(":visible").animate({ width: "toggle" });
$('#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 ( !$('#book').is(':visible')) {
alert('#book is not visible')
}
或以下是 sam, 将 jQuery 选择器保存在一个变量中, 以便在您需要它多次时有更好的性能 :
var $book = $('#book')
if(!$book.is(':visible')) {
alert('#book is not visible')
}