如何使元素的可见度.hide()
, .show()
,或.toggle()
?
如果一个元素是visible
或hidden
?
如何使元素的可见度.hide()
, .show()
,或.toggle()
?
如果一个元素是visible
或hidden
?
当前回答
如果您想要检查页面上是否可见某个元素, 取决于其父的可见度, 您可以检查是否width
和height
本要素的数值均等于0
.
jj 查询
$element.width() === 0 && $element.height() === 0
香草香草
element.clientWidth === 0 && element.clientHeight === 0
或
element.offsetWidth === 0 && element.offsetHeight === 0
其他回答
content.style.display != 'none'
function toggle() {
$(content).toggle();
let visible= content.style.display != 'none'
console.log('visible:', visible);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button onclick="toggle()">Show/hide</button>
<div id="content">ABC</div>
jQuery 解决方案, 但对于想更改按钮文字的人来说,
$(function(){
$("#showHide").click(function(){
var btn = $(this);
$("#content").toggle(function () {
btn.text($(this).css("display") === 'none' ? "Show" : "Hide");
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="showHide">Hide</button>
<div id="content">
<h2>Some content</h2>
<p>
What is Lorem Ipsum? Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.
</p>
</div>
有两种方法可以检查元素的可见度。
解决方案 # 1
if($('.selector').is(':visible')){
// element is visible
}else{
// element is hidden
}
解决方案 # 2
if($('.selector:visible')){
// element is visible
}else{
// element is hidden
}
isHidden = function(element){
return (element.style.display === "none");
};
if(isHidden($("element")) == true){
// Something
}
你可以试试这个
$(document).ready(function() {
var view = $(this).is(':visible');
if(view) {
alert("view");
// Code
}
else
{
alert("hidden");
}
});