ホームページ > ウェブフロントエンド > jsチュートリアル > プログラマーが知っておくべき 35 の jQuery コード スニペット

プログラマーが知っておくべき 35 の jQuery コード スニペット

PHPz
リリース: 2018-09-29 09:16:33
オリジナル
1316 人が閲覧しました

jQuery は現在、Web 開発で最も人気のある JavaScript ライブラリとなっており、jQuery と多数のプラグインを使用して、さまざまな素晴らしい効果を簡単に実現できます。この記事では、jQuery をより効率的に使用できるように、いくつかの実践的な jQuery スキルを紹介します。

迅速な開発に役立つ 35 の jQuery ヒント/コード スニペットを集めました。

1. 右クリックを無効にします

1

2

3

4

5

$(document).ready(function(){

  $(document).bind("contextmenu",function(e){

    return false;

  });

});

ログイン後にコピー

2. 検索テキストボックスのテキストを非表示にします

1

2

3

4

5

6

7

8

9

10

11

12

13

14

Hide when clicked in the search field, the value.(example can be found below in the comment fields)

$(document).ready(function() {

$("input.text1").val("Enter your search text here");

  textFill($('input.text1'));

});

  function textFill(input){ //input focus text function

   var originalvalue = input.val();

   input.focus( function(){

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

   });

   input.blur( function(){

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

   });

}

ログイン後にコピー

3. 新しいウィンドウでリンクを開きます

1

2

3

4

5

6

7

8

9

10

XHTML 1.0 Strict doesn't allow this attribute in the code, so use this to keep the code valid.

$(document).ready(function() {

  //Example 1: Every link will open in a new window

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

  //Example 2: Links with the rel="external" attribute will only open in a new window

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

   this.target = "_blank";

  });

});

// how to useopen link

ログイン後にコピー

4. ブラウザを検出します

注: バージョン jQuery 1.4 では、$.support が $.browser 変数を置き換えました

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

$(document).ready(function() {

// Target Firefox 2 and above

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

  // do something

}

// Target Safari

if( $.browser.safari ){

  // do something

}

// Target Chrome

if( $.browser.chrome){

  // do something

}

// Target Camino

if( $.browser.camino){

  // do something

}

// Target Opera

if( $.browser.opera){

  // do something

}

// Target IE6 and below

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

  // do something

}

});

ログイン後にコピー

5. 画像のプリロード

1

2

3

4

5

6

7

8

9

10

This piece of code will prevent the loading of all images, which can be useful if you have a site with lots of images.

$(document).ready(function() {

jQuery.preloadImages = function()

{

 for(var i = 0; i<ARGUMENTS.LENGTH; jQuery(?").attr("src", arguments[i]);

 }

}

// how to use

$.preloadImages("image1.jpg");

});

ログイン後にコピー

6. ページスタイルの切り替え

1

2

3

4

5

6

7

$(document).ready(function() {

  $("a.Styleswitcher").click(function() {

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

    $(&#39;link[rel=stylesheet]&#39;).attr(&#39;href&#39; , $(this).attr(&#39;rel&#39;));

  });

// how to use

// place this in your header// the linksDefault ThemeRed ThemeBlue Theme});

ログイン後にコピー

7. 列の高さは同じです

2 つの CSS 列が使用されている場合、このメソッドを使用して 2 つの列の高さを同じにすることができます。同じ 。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

$(document).ready(function() {

function equalHeight(group) {

  tallest = 0;

  group.each(function() {

    thisHeight = $(this).height();

    if(thisHeight > tallest) {

      tallest = thisHeight;

    }

  });

  group.height(tallest);

}

// how to use

$(document).ready(function() {

  equalHeight($(".left"));

  equalHeight($(".right"));

});

});

ログイン後にコピー

8. ページのフォント サイズを動的に制御します

ユーザーはページのフォント サイズを変更できます

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

$(document).ready(function() {

 // Reset the font size(back to default)

 var originalFontSize = $(&#39;html&#39;).css(&#39;font-size&#39;);

  $(".resetFont").click(function(){

  $(&#39;html&#39;).css(&#39;font-size&#39;, originalFontSize);

 });

 // Increase the font size(bigger font0

 $(".increaseFont").click(function(){

  var currentFontSize = $(&#39;html&#39;).css(&#39;font-size&#39;);

  var currentFontSizeNum = parseFloat(currentFontSize, 10);

  var newFontSize = currentFontSizeNum*1.2;

  $(&#39;html&#39;).css(&#39;font-size&#39;, newFontSize);

  return false;

 });

 // Decrease the font size(smaller font)

 $(".decreaseFont").click(function(){

  var currentFontSize = $(&#39;html&#39;).css(&#39;font-size&#39;);

  var currentFontSizeNum = parseFloat(currentFontSize, 10);

  var newFontSize = currentFontSizeNum*0.8;

  $(&#39;html&#39;).css(&#39;font-size&#39;, newFontSize);

  return false;

 });

});

ログイン後にコピー

9. ページの先頭関数に戻ります

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

For a smooth(animated) ride back to the top(or any location).

$(document).ready(function() {

$(&#39;a[href*=#]&#39;).click(function() {

 if (location.pathname.replace(/^\//,&#39;&#39;) == this.pathname.replace(/^\//,&#39;&#39;)

 && location.hostname == this.hostname) {

  var $target = $(this.hash);

  $target = $target.length && $target

  || $(&#39;[name=&#39; + this.hash.slice(1) +&#39;]&#39;);

  if ($target.length) {

 var targetOffset = $target.offset().top;

 $(&#39;html,body&#39;)

 .animate({scrollTop: targetOffset}, 900);

  return false;

  }

 }

 });

// how to use

// place this where you want to scroll to// the linkgo to top});

ログイン後にコピー

10. マウス ポインタの XY 値を取得します。 🎜>

1

2

3

4

5

6

7

Want to know where your mouse cursor is?

$(document).ready(function() {

  $().mousemove(function(e){

   //display the x and y axis values inside the div with the id XY

  $(&#39;#XY&#39;).html("X Axis : " + e.pageX + " | Y Axis " + e.pageY);

 });

// how to use});

ログイン後にコピー

11. トップに戻るボタン

トップに戻るアニメーションを実装するには、animate とscrollTopを使用します。他のプラグインを使用せずに。

1

2

3

4

5

6

// Back to top

$(&#39;a.top&#39;).click(function () {

 $(document.body).animate({scrollTop: 0}, 800);

 return false;

});

Back to top

ログイン後にコピー
scrollTop の値を変更することでリターンとトップの間の距離を調整できます。animate の 2 番目のパラメータはリターン動作の実行に必要な時間 (単位: ミリ秒) )。

12. 画像のプリロード

ページで非表示の画像 (ホバー表示など) が多数使用されている場合は、それらをプリロードする必要がある場合があります:

1

2

3

4

5

6

$.preloadImages = function () {

 for (var i = 0; i < arguments.length; i++) {

  $(&#39;&#39;).attr(&#39;src&#39;, arguments[i]);

 }

};

$.preloadImages(&#39;img/hover1.png&#39;, &#39;img/hover2.png&#39;);

ログイン後にコピー

13. 画像がロードされているかどうかを確認します

次の操作を実行するために、画像がロードされていることを確認する必要がある場合があります。 >

1

2

3

$(&#39;img&#39;).load(function () {

 console.log(&#39;image load successful&#39;);

});

ログイン後にコピー
img を他の ID またはクラスに置き換えて、指定したイメージが読み込まれているかどうかを確認できます。

14. 壊れた画像を自動的に修正する

Web サイト上で壊れた画像リンクを見つけた場合は、簡単に置き換えることができない画像に置き換えることができます。 。この簡単なコードを追加すると、多くの問題を軽減できます:

1

2

3

$(&#39;img&#39;).on(&#39;error&#39;, function () {

 $(this).prop(&#39;src&#39;, &#39;img/broken.png&#39;);

});

ログイン後にコピー
サイトに壊れた画像リンクがない場合でも、このコードを追加しても問題はありません。

15. マウスホバー (hover) 切り替えクラス属性

ユーザーがクリック可能な要素の上にマウスを置いたときの効果を変更したい場合は、次のコードを使用します。要素の上にマウスを移動するとクラス属性を追加でき、ユーザーがマウスを離すとクラス属性を自動的にキャンセルできます:


1

2

3

4

5

6

7

8

9

$(&#39;.btn&#39;).hover(function () {

 $(this).addClass(&#39;hover&#39;);

 }, function () {

  $(this).removeClass(&#39;hover&#39;);

 });

你只需要添加必要的CSS代码即可。如果你想要更简洁的代码,可以使用 toggleClass 方法:

$(&#39;.btn&#39;).hover(function () {

 $(this).toggleClass(&#39;hover&#39;);

});

ログイン後にコピー
注: CSS を直接使用して実現します。この効果はより良い解決策である可能性がありますが、その方法を知る必要があります。

16. 入力フィールドを無効にする

ユーザーが何らかのアクションを実行するまで、フォームの送信ボタンまたは入力フィールドを無効にする必要がある場合があります (たとえば、「読み取り」をチェックします)条件」チェックボックス)。無効な属性は、有効にするまで追加できます:


必要なのは、removeAttr メソッドを実行し、削除する属性をパラメータとして渡すことだけです:

1

$(&#39;input[type="submit"]&#39;).prop(&#39;disabled&#39;, true);

ログイン後にコピー


1

$(&#39;input[type="submit"]&#39;).removeAttr(&#39;disabled&#39;);

ログイン後にコピー
17. リンクの読み込みを防止する

ページにリンクしたくない、またはページをリロードしたくない場合は、別のことをしたい場合があります。または何かをトリガーする 他のスクリプトの場合は、次のようにすることができます:


1

2

3

$(&#39;a.no-link&#39;).click(function (e) {

 e.preventDefault();

});

ログイン後にコピー
18. フェード/スライドを切り替えます

スライドは私たちが使用するものです アニメーション効果は、要素の見栄えを良くするために jQuery でよく使用されます。ただし、要素が表示されるときに最初の効果が使用され、要素が消えるときに 2 番目の効果が使用されるようにしたい場合は、次のようにすることができます:


1

2

3

4

5

6

7

8

// Fade

$(&#39;.btn&#39;).click(function () {

 $(&#39;.element&#39;).fadeToggle(&#39;slow&#39;);

});

// Toggle

$(&#39;.btn&#39;).click(function () {

 $(&#39;.element&#39;).slideToggle(&#39;slow&#39;);

});

ログイン後にコピー
19. シンプルなアコーディオン効果

アコーディオン効果を実現する簡単な方法は次のとおりです:


1

2

3

4

5

6

7

8

9

// Close all panels

$(&#39;#accordion&#39;).find(&#39;.content&#39;).hide();

// Accordion

$(&#39;#accordion&#39;).find(&#39;.accordion-header&#39;).click(function () {

 var next = $(this).next();

 next.slideToggle(&#39;fast&#39;);

 $(&#39;.content&#39;).not(next).slideUp(&#39;fast&#39;);

 return false;

});

ログイン後にコピー
20. 2 つの DIV を同じ高さにする

内部のコンテンツに関係なく、2 つの DIV を同じ高さにする必要がある場合があります。次のコード スニペットを使用できます:

1

2

3

4

5

6

7

8

var $columns = $(&#39;.column&#39;);

var height = 0;

$columns.each(function () {

 if ($(this).height() > height) {

  height = $(this).height();

 }

});

$columns.height(height);

ログイン後にコピー
このコードは、要素のグループをループし、要素の高さを要素内の最大の高さに設定します。

21. 要素が空かどうかを確認します

1

2

3

4

5

6

This will allow you to check if an element is empty.

$(document).ready(function() {

 if ($(&#39;#id&#39;).html()) {

  // do something

  }

});

ログイン後にコピー
22. 要素

1

2

3

$(document).ready(function() {

  $(&#39;#id&#39;).replaceWith(&#39;I have been replaced&#39;);

});

ログイン後にコピー
23. jQuery 遅延読み込み関数

1

2

3

4

5

$(document).ready(function() {

  window.setTimeout(function() {

   // do something

  }, 1000);

});

ログイン後にコピー
24. 🎜>

25. 要素が jquery オブジェクト コレクションに存在するかどうかを確認します

1

2

3

4

$(document).ready(function() {

  var el = $(&#39;#id&#39;);

  el.html(el.html().replace(/word/ig, ""));

});

ログイン後にコピー

26 . DIV 全体をクリック可能にします

1

2

3

4

5

$(document).ready(function() {

  if ($(&#39;#id&#39;).length) {

 // do something

 }

});

ログイン後にコピー

27. ID与Class之间转换

当改变Window大小时,在ID与Class之间切换

1

2

3

4

5

6

7

8

9

10

11

$(document).ready(function() {

  function checkWindowSize() {

  if ( $(window).width() > 1200 ) {

    $(&#39;body&#39;).addClass(&#39;large&#39;);

  }

  else {

    $(&#39;body&#39;).removeClass(&#39;large&#39;);

  }

  }

$(window).resize(checkWindowSize);

});

ログイン後にコピー

28. 克隆对象

1

2

3

$(document).ready(function() {

  var cloned = $(&#39;#id&#39;).clone();

// how to use});

ログイン後にコピー

29. 使元素居屏幕中间位置

1

2

3

4

5

6

7

8

9

$(document).ready(function() {

 jQuery.fn.center = function () {

   this.css("position","absolute");

   this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");

   this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");

   return this;

 }

 $("#id").center();

});

ログイン後にコピー

30. 写自己的选择器

1

2

3

4

5

6

7

8

9

10

11

$(document).ready(function() {

  $.extend($.expr[&#39;:&#39;], {

    moreThen1000px: function(a) {

      return $(a).width() > 1000;

   }

  });

 $(&#39;.box:moreThen1000px&#39;).click(function() {

   // creating a simple js alert box

   alert(&#39;The element that you have clicked is over 1000 pixels wide&#39;);

 });

});

ログイン後にコピー

31. 统计元素个数

1

2

3

$(document).ready(function() {

  $("p").size();

});

ログイン後にコピー

32. 使用自己的 Bullets

1

2

3

4

5

6

$(document).ready(function() {

  $("ul").addClass("Replaced");

  $("ul > li").prepend("‒ ");

 // how to use

 ul.Replaced { list-style : none; }

});

ログイン後にコピー

33. 引用Google主机上的Jquery类库

1

//Example 1

ログイン後にコピー

34. 禁用Jquery(动画)效果

1

2

3

$(document).ready(function() {

  jQuery.fx.off = true;

});

ログイン後にコピー

35. 与其他Javascript类库冲突解决方案

1

2

3

4

$(document).ready(function() {

  var $jq = jQuery.noConflict();

  $jq(&#39;#id&#39;).show();

});

ログイン後にコピー

以上就是本章的全部内容,更多相关教程请访问jQuery视频教程

関連ラベル:
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
人気のおすすめ
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート