jQueryは1つの要素が見えるかどうかを判断する方法

1802 ワード

この例では、jQueryが要素が見えるかどうかを判断する方法について説明します.皆さんの参考にしてください.具体的には以下の通りです.
jQueryは、1つの要素が可視または非表示であることを容易に決定し、それぞれ異なる処理を行うことができる.例えば、あるdivが見えるかどうかによって、ボタンに異なる文字とアイコンを表示したいです.次のように実現できます.
方法1:

$('#para_div button').click(function() {  
   if($(this).next().is(":visible")) {        
    //$(this).html('  ');  
    $(this).css({"background":"url(/images/btn_arrow_down.png) no-repeat"});  
   }  
   else {  
    //$(this).html('  ');   
    $(this).css({"background":"url(/images/btn_arrow_up.png) no-repeat"});    
   }   
  $(this).next().slideToggle('fast');  
 });


方法2:

$('#para_div button').click(function() {  
   if($(this).next().css('display') == 'none') {        
    //$(this).html('  ');   
 $(this).css({"background":"url(/images/btn_arrow_up.png) no-repeat"});
   }  
   else{  
    //$(this).html('  ');  
 $(this).css({"background":"url(/images/btn_arrow_down.png) no-repeat"});   
   }   
  $(this).next().slideToggle('fast');  
});

方法3:

$('#para_div button').click(function() {  
 var $cn = $(this).next();  
 //$(this).html(($cn.is(":visible")) ? '  ' : '  ');  
(this).css(($cn.is(":visible")) ?  
{"background":"url(images/btn_arrow_down.png) no-repeat"} :  
{"background":"url(images/btn_arrow_up.png) no-repeat"});  
 $cn.toggle('fast');
});


本文で述べたことが皆さんのjQueryプログラム設計に役立つことを願っています.