如何使元素的可见度.hide()
, .show()
,或.toggle()
?
如果一个元素是visible
或hidden
?
如何使元素的可见度.hide()
, .show()
,或.toggle()
?
如果一个元素是visible
或hidden
?
当前回答
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>
其他回答
可以创建一个函数来检查可见度/显示属性,以便测量该元素是否显示在界面中。
function checkUIElementVisible(element) {
return ((element.css('display') !== 'none') && (element.css('visibility') !== 'hidden'));
}
$('someElement').on('click', function(){ $('elementToToggle').is(':visible')
就是这样jj 查询内部解决这个问题 :
jQuery.expr.pseudos.visible = function( elem ) {
return !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length );
};
如果您不使用 jQuery, 您可以使用这个代码, 并将其转换为您自己的功能 :
function isVisible(elem) {
return !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length );
};
哪个isVisible
将返回true
只要元素是可见的。
人们可以简单地使用hidden
或visible
属性, 如 :
$('element:hidden')
$('element:visible')
或者您可以简化相同的是如下所示。
$(element).is(":visible")
这里有一个永久有条件的表达式 来检查元素的状态 然后切换它:
$('someElement').on('click', function(){ $('elementToToggle').is(':visible') ? $('elementToToggle').hide('slow') : $('elementToToggle').show('slow'); });