如何使元素的可见度.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>
其他回答
您可以使用这个:
$(element).is(':visible');
$(document).ready(function()
{
$("#toggle").click(function()
{
$("#content").toggle();
});
$("#visiblity").click(function()
{
if( $('#content').is(':visible') )
{
alert("visible"); // Put your code for visibility
}
else
{
alert("hidden");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<p id="content">This is a Content</p>
<button id="toggle">Toggle Content Visibility</button>
<button id="visibility">Check Visibility</button>
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>
$( "div:visible" ).click(function() {
$( this ).css( "background", "yellow" );
});
$( "button" ).click(function() {
$( "div:hidden" ).show( "fast" );
});
API 文献资料:可见可见选择器
我只是想澄清,在jQuery,
某些要素可被视为隐藏,原因如下:
- 它们有一个 CSS 显示值, 没有任何值 。
- 它们组成元素 类型 = "隐藏" 。
- 它们的宽度和高度明确定为0。
- 隐藏了祖先元素,所以该元素不在页面上显示。
具有可见度的要素: 隐藏或不透明: 0 被视为可见, 因为它们仍然在布局中消耗空间 。 在隐藏元素的动画中, 该元素被视为可见, 直到动画结束 。
资料来源:隐藏选择器 jQuery API 文件
if($('.element').is(':hidden')) {
// Do something
}
$('someElement').on('click', function(){ $('elementToToggle').is(':visible')