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

jopen 10年前發布 | 28K 次閱讀 jQuery

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

平滑滾動到頁面頂部

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

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

克隆表頭至表的底部

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

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

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

加載外部內容

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

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

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

等高列

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

var maxheight = 0;
$("div.col").each(function(){
  if($(this).height() > maxheight) { maxheight = $(this).height(); }
});

$("div.col").height(maxheight);

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

Table Stripes (Zebra)

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

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

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

部分頁面刷新

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

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

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

預先載入圖像

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

$.preloadImages = function() {
       for(var i = 0; i<arguments.length; i++) {
               $("<img />").attr("src", arguments[i]);
       }
}

$(document).ready(function() {
       $.preloadImages("hoverimage1.jpg","hoverimage2.jpg");
});

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

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

$('a').each(function() {
   var a = new RegExp('/' + window.location.host + '/');
   if(!a.test(this.href)) {
       $(this).click(function(event) {
           event.preventDefault();
           event.stopPropagation();
           window.open(this.href, '_blank');
       });
   }
});

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

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

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

// global vars
var winWidth = $(window).width();
var winHeight = $(window).height();

// set initial div height / width
$('div').css({
    'width': winWidth,
'height': winHeight,
});

// make sure div stays full width/height on resize
$(window).resize(function(){
    $('div').css({
    'width': winWidth,
    'height': winHeight,
});
});

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

測試密碼強度

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

首先,假設此HTML:

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

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

$('#pass').keyup(function(e) {
     var strongRegex = new RegExp("^(?=.{8,})(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\\W).*$", "g");
     var mediumRegex = new RegExp("^(?=.{7,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))).*$", "g");
     var enoughRegex = new RegExp("(?=.{6,}).*", "g");
     if (false == enoughRegex.test($(this).val())) {
             $('#passstrength').html('More Characters');
     } else if (strongRegex.test($(this).val())) {
             $('#passstrength').className = 'ok';
             $('#passstrength').html('Strong!');
     } else if (mediumRegex.test($(this).val())) {
             $('#passstrength').className = 'alert';
             $('#passstrength').html('Medium!');
     } else {
             $('#passstrength').className = 'error';
             $('#passstrength').html('Weak!');
     }
     return true;
});

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

使用jQuery調整圖像大小

$(window).bind("load", function() {
    // IMAGE RESIZE
    $('#product_cat_list img').each(function() {
        var maxWidth = 120;
        var maxHeight = 120;
        var ratio = 0;
        var width = $(this).width();
        var height = $(this).height();

        if(width > maxWidth){
            ratio = maxWidth / width;
            $(this).css("width", maxWidth);
            $(this).css("height", height * ratio);
            height = height * ratio;
        }
        var width = $(this).width();
        var height = $(this).height();
        if(height > maxHeight){
            ratio = maxHeight / height;
            $(this).css("height", maxHeight);
            $(this).css("width", width * ratio);
            width = width * ratio;
        }
    });
    //$("#contentpage img").show();
    // IMAGE RESIZE
});

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

頁面滾動時自動加載內容

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

var loading = false;
$(window).scroll(function(){
    if((($(window).scrollTop()+$(window).height())+250)>=$(document).height()){
        if(loading == false){
            loading = true;
            $('#loadingbar').css("display","block");
            $.get("load.php?start="+$('#loaded_max').val(), function(loaded){
                $('body').append(loaded);
                $('#loaded_max').val(parseInt($('#loaded_max').val())+50);
                $('#loadingbar').css("display","none");
                loading = false;
            });
        }
    }
});

$(document).ready(function() {
    $('#loaded_max').val(50);
});

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

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

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

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

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

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

$(function() {
    $.fn.sortList = function() {
    var mylist = $(this);
    var listitems = $('li', mylist).get();
    listitems.sort(function(a, b) {
        var compA = $(a).text().toUpperCase();
        var compB = $(b).text().toUpperCase();
        return (compA < compB) ? -1 : 1;
    });
    $.each(listitems, function(i, itm) {
        mylist.append(itm);
    });
   }

    $("ul#demoOne").sortList();

});

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

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!