jQueryの実用的なテクニック

7629 ワード


1.右クリック禁止
1 $(function(){

2    $(document).bind('contextmenu', function(e){

3       return false;     

4     }) 

5 })

 
2.検索テキストボックスのテキストを非表示にする
 1 $(function(){

 2   $('input.text').val('enter text here');

 3   textFill($('input.text'));

 4 });

 5 

 6 function textFill(text){

 7   var originalValue = input.val();

 8   input.focus(function(){

 9     if($.trim(input.val())==originalValue ) { input.val(''); }

10   });

11   input.blur(function(){

12     if($.trim(input.val())=='') { input.val(originalValue); }

13   });

14 }

 
3.新しいウィンドウでリンクを開く
 1 $(function(){

 2   //every link will open in a new window

 3   $('a[href^="http://"]').attr('target', '_blank');

 4   

 5   //attribute rel='external' will only open in a new window

 6   $('a[@rel$="external"]').click(function(){

 7     this.target='_blank';

 8   });

 9 });

10 

11 

12 <A href="http://www.baidu.com" rel=external>open link</A> 

 
4.検出ブラウザ
$(function(){

  //firefox 2 and above

  if($.browser.mozilla && $.browser.version >= "1.8"){

    //do what you want

  }



  if($.browser.safari){

    //do what you want

  }



  if($.browser.chrome){

    //do what you want

  }



  if($.browser.camino){

    //do what you want

  }



  if($.browser.opera){

    //do what you want

  }



  if($.browser.msie && $.browser.version <= 6){

    //do what you want

  }



  if($.browser.msie && $.browser.version > 6){

    //do what you want

  }



})

 
5.ページスタイルの切り替え
 1 $(function(){

 2   $('a.Styleswitcher').click(function(){ 

 3      //swicth the LINK REL attribute with the value in A REL attribute 

 4      $('link[rel=stylesheet]').attr('href' , $(this).attr('rel')); 

 5   }); 

 6   // how to use 

 7   // place this in your header 

 8   <LINK href="default.css" type=text/css rel=stylesheet> 

 9   // the links 

10   <A class=Styleswitcher href="#" rel=default.css>Default Theme</A> 

11   <A class=Styleswitcher href="#" rel=red.css>Red Theme</A> 

12   <A class=Styleswitcher href="#" rel=blue.css>Blue Theme</A> 

13 });