如何使元素的可见度.hide()
, .show()
,或.toggle()
?
如果一个元素是visible
或hidden
?
如何使元素的可见度.hide()
, .show()
,或.toggle()
?
如果一个元素是visible
或hidden
?
当前回答
$(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>
其他回答
使用任何可见的选择器或隐藏的选择器检查粘度 :
使用.toggle ()- 显示和隐藏元素
function checkVisibility() {
// check if element is hidden or not and return true false
console.log($('#element').is(':hidden'));
// check if element is visible or not and return true false
console.log($('#element').is(':visible'));
if ( $('#element').css('display') == 'none' || $('#element').css("visibility") == "hidden"){
console.log('element is hidden');
} else {
console.log('element is visibile');
}
}
checkVisibility()
$('#toggle').click(function() {
$('#element').toggle()
checkVisibility()
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id='toggle'>Toggle</button>
<div style='display:none' id='element'>
<h1>Hello</h1>
<p>it's visible</p>
</div>
$('#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"/>
来源(来自我的博客):
您可以通过使用:visible
和:hidden
选择器。
var isVisible = $('#myDiv').is(':visible');
var isHidden = $('#myDiv').is(':hidden');
如果你只是根据它的能见度 依据一个元素行事 你可以包括:visible
或:hidden
在选择表达式中。例如:
$('#myDiv:visible').animate({left: '+=200px'}, 'slow');
因为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;
}
});