10+個方便,可重複使用的jQuery代碼片段

多年來,jQuery已經成爲每個Web開發人員必須使用的一個JS庫。它使用簡單,速度快,功能非常強大。在這篇文章中分享給大家一系列的10+個得心應手的jQuery代碼片段。

平滑滾動到頁面頂部

1 $("a[href='#top']").click(function() {
2   $("html, body").animate({ scrollTop: 0 }, "slow");
3   return false;
4 });

來源: http://stackoverflow.com/questions/1144805/how-do-i-scroll…

克隆表頭至表的底部

將表頭複製一份到表的底部,可以讓你的表格更具可讀性。

1 var $tfoot = $('<tfoot></tfoot>');
2 $($('thead').clone(true, true).children().get().reverse()).each(function(){
3     $tfoot.append($(this));
4 });
5 $tfoot.insertAfter('table thead');

來源: http://lunart.com.ua/jquery

加載外部內容

你是否需要加載一些外部內容到一個div中?利用jQuery就很容易做到,如下面的例子:

1 $("#content").load("somefile.html", function(response, status, xhr) {
2   // error handling
3   if(status == "error") {
4     $("#content").html("An error occured: " + xhr.status + " " + xhr.statusText);
5   }
6 });

來源: http://api.jquery.com/load/

等高列

當你使用的列個來顯示您網站內容,如果列有同等的高度,它肯定更好看。下面的代碼將對所有div元素增加.col類。並會根據最大的元素調整自己的高度。超好用!

1 var maxheight = 0;
2 $("div.col").each(function(){
3   if($(this).height() > maxheight) { maxheight = $(this).height(); }
4 });
5   
6 $("div.col").height(maxheight);

來源: http://web.enavu.com/tutorials/top-10-jquery-snippets-including-jquery-1-4/

Table Stripes (Zebra)

當在表上顯示的數據,每一行交替顏色肯定會增加可讀性。這裏有一個片段,幫你自動實現這種效果。

1 $(document).ready(function(){                             
2      $("table tr:even").addClass('stripe');
3 });

來源: http://www.alovefordesign.com/5-jquery-must-have-code-snippets/

部分頁面刷新

如果你只需要刷新頁面的某一部分,下面的3行代碼就能夠實現。在這個例子中,一個#refresh div會每10秒自動刷新。

1 setInterval(function() {
2 $("#refresh").load(location.href+" #refresh>*","");
3 }, 10000); // milliseconds to wait

來源: http://web.enavu.com/tutorials/top-10-jquery-snippets-including-jquery-1-4/

預先載入圖像

利用jQuery能夠很方便實現在後臺,預先加載圖片。以下8行代碼就能夠實現。.

1 $.preloadImages = function() {
2        for(var i = 0; i<arguments.length; i++) {
3                $("<img />").attr("src", arguments[i]);
4        }
5 }
6   
7 $(document).ready(function() {
8        $.preloadImages("hoverimage1.jpg","hoverimage2.jpg");
9 });

來源: http://css-tricks.com/snippets/jquery/image-preloader/

在新標籤/窗口中打開外部鏈接

01 $('a').each(function() {
02    var a = new RegExp('/' + window.location.host + '/');
03    if(!a.test(this.href)) {
04        $(this).click(function(event) {
05            event.preventDefault();
06            event.stopPropagation();
07            window.open(this.href, '_blank');
08        });
09    }
10 });

來源: http://css-tricks.com/snippets/jquery/open-external-links-in-new-window/

利用jQuery實現Div佔滿一個viewport的寬/高

這一段代碼允許您根據viewport大小創建一個全寬/全高的div。該代碼也可以調整窗口大小。實現強大模態對話框或彈出窗口。

01 // global vars
02 var winWidth = $(window).width();
03 var winHeight = $(window).height();
04   
05 // set initial div height / width
06 $('div').css({
07     'width': winWidth,
08 'height': winHeight,
09 });
10   
11 // make sure div stays full width/height on resize
12 $(window).resize(function(){
13     $('div').css({
14     'width': winWidth,
15     'height': winHeight,
16 });
17 });

來源: http://www.jqueryrain.com/2013/03/div-full-widthheight-of-viewport-with-jquery/

測試密碼強度

當你讓用戶定義自己的密碼,它通常是一件好事,表明有多強密碼。這正是這段代碼做。

首先,假設此HTML:

1 <input type="password" name="pass" id="pass" />
2 <span id="passstrength"></span>

這裏是相應的jQuery代碼。所輸入的密碼將使用正則表達式進行評估和消息將被返回給用戶,讓他知道,如果他所選擇的密碼爲強,中,弱,或太短。

01 $('#pass').keyup(function(e) {
02      var strongRegex = new RegExp("^(?=.{8,})(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\\W).*$", "g");
03      var mediumRegex = new RegExp("^(?=.{7,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))).*$", "g");
04      var enoughRegex = new RegExp("(?=.{6,}).*", "g");
05      if (false == enoughRegex.test($(this).val())) {
06              $('#passstrength').html('More Characters');
07      } else if (strongRegex.test($(this).val())) {
08              $('#passstrength').className = 'ok';
09              $('#passstrength').html('Strong!');
10      } else if (mediumRegex.test($(this).val())) {
11              $('#passstrength').className = 'alert';
12              $('#passstrength').html('Medium!');
13      } else {
14              $('#passstrength').className = 'error';
15              $('#passstrength').html('Weak!');
16      }
17      return true;
18 });

來源: http://css-tricks.com/snippets/jquery/password-strength/

使用jQuery調整圖像大小

01 $(window).bind("load", function() {
02     // IMAGE RESIZE
03     $('#product_cat_list img').each(function() {
04         var maxWidth = 120;
05         var maxHeight = 120;
06         var ratio = 0;
07         var width = $(this).width();
08         var height = $(this).height();
09       
10         if(width > maxWidth){
11             ratio = maxWidth / width;
12             $(this).css("width", maxWidth);
13             $(this).css("height", height * ratio);
14             height = height * ratio;
15         }
16         var width = $(this).width();
17         var height = $(this).height();
18         if(height > maxHeight){
19             ratio = maxHeight / height;
20             $(this).css("height", maxHeight);
21             $(this).css("width", width * ratio);
22             width = width * ratio;
23         }
24     });
25     //$("#contentpage img").show();
26     // IMAGE RESIZE
27 });

來源: http://snipplr.com/view/62552/mage-resize/

頁面滾動時自動加載內容

一些網站如Twitter在頁面滾動時會加載內容。這意味着,所有內容都在一個頁面上,只要你向下滾動就會動態加載。
下面這段代碼可以實現這樣的效果。

01 var loading = false;
02 $(window).scroll(function(){
03     if((($(window).scrollTop()+$(window).height())+250)>=$(document).height()){
04         if(loading == false){
05             loading = true;
06             $('#loadingbar').css("display","block");
07             $.get("load.php?start="+$('#loaded_max').val(), function(loaded){
08                 $('body').append(loaded);
09                 $('#loaded_max').val(parseInt($('#loaded_max').val())+50);
10                 $('#loadingbar').css("display","none");
11                 loading = false;
12             });
13         }
14     }
15 });
16   
17 $(document).ready(function() {
18     $('#loaded_max').val(50);
19 });

來源: http://fatfolderdesign.com/173/content-load-on-scroll-with-jquery

檢查一個圖像是否已經加載

這裏有一個片段,用來判斷、一個圖像是否已經加載。

1 var imgsrc = 'img/image1.png';
2 $('<img/>').load(function () {
3     alert('image loaded');
4 }).error(function () {
5     alert('error loading image');
6 }).attr('src', imgsrc);

來源: http://tympanus.net/codrops/2010/01/05/some-useful…

按字母順序對列表進行排序

01 $(function() {
02     $.fn.sortList = function() {
03     var mylist = $(this);
04     var listitems = $('li', mylist).get();
05     listitems.sort(function(a, b) {
06         var compA = $(a).text().toUpperCase();
07         var compB = $(b).text().toUpperCase();
08         return (compA < compB) ? -1 : 1;
09     });
10     $.each(listitems, function(i, itm) {
11         mylist.append(itm);
12     });
13    }
14   
15     $("ul#demoOne").sortList();
16   
17 });

來源: http://stackoverflow.com/questions/13394796/javascript-jquery-to-sort…

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章