10+个方便,可重复使用的jQuery代码片段

jopen 10年前

多年来,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…