如何使元素的可见度.hide(), .show(),或.toggle()?

如果一个元素是visiblehidden?


当前回答

使用类切换,而不是样式编辑.

使用指定用于“隐藏”元素的分类很简单,也是最有效的方法之一。Display“ 无” 样式的“ 无” 样式的性能将比直接编辑该样式更快。 我在 Stack 溢出问题中非常透彻地解释了其中的一些内容 。在同一 div 中将两个元素转换为可见/隐藏.


JavaScript 最佳做法和优化

Google前端工程师Nicholas Zakas在Google Tech Talk的影片中,

  • 加快您的 Javastramp 速度(YouTube) (YouTube) (YouTube) (YouTube) (YouTube) (YouTube) (YouTube) (YouTube) (YouTube) (YouTube) (YouTube) (YouTube) (YouTube)

其他回答

expect($("#message_div").css("display")).toBe("none");

此选项可以检查标签是否可见

 // using a pure CSS selector  
   if ($('p:visible')) {  
      alert('Paragraphs are visible (checked using a CSS selector) !');  
   };  
  
   // using jQuery's is() method  
   if ($('p').is(':visible')) {  
      alert('Paragraphs are visible (checked using is() method)!');  
   };  
  
   // using jQuery's filter() method  
   if ($('p').filter(':visible')) {  
      alert('Paragraphs are visible (checked using filter() method)!');  
   };  
  
   // you can use :hidden instead of :visible to reverse the logic and check if an element is hidden  
   // if ($('p:hidden')) {  
   //    do something  
   // };  

$(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>

if($("h1").is(":hidden")){
    // your code..
}

由于问题只涉及一个要素,本守则可能更适合:

// Checks CSS content for display:[none|block], ignores visibility:[true|false]
$(element).is(":visible");

// The same works with hidden
$(element).is(":hidden");

twernt的建议,但适用于单一个元素;并且匹配 jQuery FAQ 中推荐的算法.

我们用jQuery的是( )将选中的元素与其它元素、选择器或任何 jQuery 对象一起检查。此方法沿 DOM 元素沿 DOM 元素查找匹配,该匹配符合所传递的参数。如果匹配,则返回为真实,否则返回为虚假。