多年来,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');
加载外部内容
你是否需要加载一些外部内容到一个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);
Table Stripes (Zebra)
当在表上显示的数据,每一行交替颜色肯定会增加可读性。这里有一个片段,帮你自动实现这种效果。
1
$(document).ready(function(){
2
$("table tr:even").addClass('stripe');
3
});
部分页面刷新
如果你只需要刷新页面的某一部分,下面的3行代码就能够实现。在这个例子中,一个#refresh
div会每10秒自动刷新。
1
setInterval(function() {
2
$("#refresh").load(location.href+" #refresh>*","");
3
}, 10000); // milliseconds to wait
预先载入图像
利用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
});
检查一个图像是否已经加载
这里有一个片段,用来判断、一个图像是否已经加载。
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
});