如何使元素的可见度.hide()
, .show()
,或.toggle()
?
如果一个元素是visible
或hidden
?
如何使元素的可见度.hide()
, .show()
,或.toggle()
?
如果一个元素是visible
或hidden
?
当前回答
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>
因为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;
}
});
测试一个元素时:hidden
在 jQuery 中选择器一个绝对定位元素可能被确认为隐藏,尽管其子元素是可见的.
虽然仔细看一看jQuery文件提供了相关信息,
要素可被视为隐藏,原因如下:[.]其宽度和高度明确定为0。 [.]
因此,在框模型和元素的计算样式方面,这实际上是有道理的。即使没有设置宽度和高度明确无误可设定 0 个至 0个隐含.
举例如下:
console.log($('.foo').is(':hidden')); // true
console.log($('.bar').is(':hidden')); // false
.foo {
position: absolute;
left: 10px;
top: 10px;
background: #ff0000;
}
.bar {
position: absolute;
left: 10px;
top: 10px;
width: 20px;
height: 20px;
background: #0000ff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="foo">
<div class="bar"></div>
</div>
jQuery 3. x 的更新 :
当 j 查询 3 时, 描述的行为将会改变 ! 如果元素有任何布局框, 包括宽度和/ 或高度为零的布局框, 元素将被视为可见 。
JSF与jQuery 3. 0.0- 阿尔法1:
同样的 JavaScript 代码将会有此输出 :
console.log($('.foo').is(':hidden')); // false
console.log($('.bar').is(':hidden')); // false
if($('#id_element').is(":visible")){
alert('shown');
}else{
alert('hidden');
}
expect($("#message_div").css("display")).toBe("none");