方便实用的jQuery代码
平滑滚动到页面顶部
我们以一个热门,实用的代码片段开始:下面的4行jquery代码,页面访问者通过点击id 为[#top],滑动到页面的顶部;
克隆表格的表头到表格底部
为了使自己的表格可读性更强,将表格的表头克隆到表格底部是个不错的注意。下面就是这个实用的代码片段。
加载外部内容
你需要添加外部内容到div标签么?如果使用jquery,这就变得很简单,具体实例如下:
相同高度的标签纵列
当你的网站是用纵列来显示的内容是,如果所有的模块列都是等高度的将会更好看,更整洁。下面的代码将会,将为所有类为.col的div标签自适应为(所有纵列高度最高)的等高模块:
表格的条纹(斑马条纹)
在表格上展示数据时,颜色交替无疑会增加可读性;下面这段代码,将为两行中间的的一行自动加上CSS类(css类自己定义):
页面局部刷新
如果你需要刷新页面的一部分,下面会有一定的帮助,只需要3行代码。在这个例子中,#refresh div每10秒自动刷新:
Preload images
jQuery轻松预载图像背景中的游客不会永远等待时,他们将要显示的图像。此代码可以使用,更新图像列表只需8行:
在新标签/窗口打开链接
target=”blank”属性允许你链接在新窗口打开的力量。当打开一个新窗口或标签的外部链接是相关,同域的链接一定要在同一个窗口中打开。
此代码检测,如果一个链接是外部的,如果是,增加了一个目标 target=”blank”的属性给它。
使用jQuery让div满宽度/高度
这个方便的代码允许你根据视图窗口创建一个全屏宽度/高度的div。代码也处理窗口大小调整。对模态对话框或弹出窗口来说不错。
检验密码强度
当你让用户定义的密码时,这是表示密码一般是多么强大的好东西。这就是下面代码要做的事:
首先,假设HTML是:
<input type="password" name="pass" id="pass" />
<span id="passstrength"></span>
这里是相应的jQuery代码。输入的密码将被评估使用正则表达式和一个消息将被返回给用户,让他知道如果他选择的密码强,中,弱,或过短。
[codes=js]
$('#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;
});
[/codes]
使用jQuery调整图像大小
尽管你应该调整您的图像在服务器端(使用PHP和GD)。使用jQuery调整图像也非常有用。下面的代码将诠释怎么用。
页面滚动自动加载内容
一些网站如Twitter通过滚动加载内容。这意味着一个页面所有的内容是通过你向下滚动来实现动态加载的。
这里将介绍怎么做的,你可以复制到自己网站看看效果:
检查图片是否已加载
这段代码是我使用图片时经常用到的,它是了解一个图片是否加载完毕最好的方式:
列表按字母顺序排列
在某些场景,按照字母顺序来排列一个长长的列表将非常有用,这段代码可以将任何列表按元字母顺序排序:
我们以一个热门,实用的代码片段开始:下面的4行jquery代码,页面访问者通过点击id 为[#top],滑动到页面的顶部;
$("a[href='#top']").click(function() { $("html, body").animate({ scrollTop: 0 }, "slow"); return false; });
克隆表格的表头到表格底部
为了使自己的表格可读性更强,将表格的表头克隆到表格底部是个不错的注意。下面就是这个实用的代码片段。
var $tfoot = $('<tfoot></tfoot>'); $($('thead').clone(true, true).children().get().reverse()).each(function(){ $tfoot.append($(this)); }); $tfoot.insertAfter('table thead');
加载外部内容
你需要添加外部内容到div标签么?如果使用jquery,这就变得很简单,具体实例如下:
$("#content").load("somefile.html", function(response, status, xhr) { // error handling if(status == "error") { $("#content").html("An error occured: " + xhr.status + " " + xhr.statusText); } });
相同高度的标签纵列
当你的网站是用纵列来显示的内容是,如果所有的模块列都是等高度的将会更好看,更整洁。下面的代码将会,将为所有类为.col的div标签自适应为(所有纵列高度最高)的等高模块:
var maxheight = 0; $("div.col").each(function(){ if($(this).height() > maxheight) { maxheight = $(this).height(); } }); $("div.col").height(maxheight);
表格的条纹(斑马条纹)
在表格上展示数据时,颜色交替无疑会增加可读性;下面这段代码,将为两行中间的的一行自动加上CSS类(css类自己定义):
$(document).ready(function(){ $("table tr:even").addClass('stripe'); });
页面局部刷新
如果你需要刷新页面的一部分,下面会有一定的帮助,只需要3行代码。在这个例子中,#refresh div每10秒自动刷新:
setInterval(function() { $("#refresh").load(location.href+" #refresh>*",""); }, 10000); // milliseconds to wait
Preload images
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"); });
在新标签/窗口打开链接
target=”blank”属性允许你链接在新窗口打开的力量。当打开一个新窗口或标签的外部链接是相关,同域的链接一定要在同一个窗口中打开。
此代码检测,如果一个链接是外部的,如果是,增加了一个目标 target=”blank”的属性给它。
$('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'); }); } });
使用jQuery让div满宽度/高度
这个方便的代码允许你根据视图窗口创建一个全屏宽度/高度的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, }); });
检验密码强度
当你让用户定义的密码时,这是表示密码一般是多么强大的好东西。这就是下面代码要做的事:
首先,假设HTML是:
<input type="password" name="pass" id="pass" />
<span id="passstrength"></span>
这里是相应的jQuery代码。输入的密码将被评估使用正则表达式和一个消息将被返回给用户,让他知道如果他选择的密码强,中,弱,或过短。
[codes=js]
$('#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;
});
[/codes]
使用jQuery调整图像大小
尽管你应该调整您的图像在服务器端(使用PHP和GD)。使用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 });
页面滚动自动加载内容
一些网站如Twitter通过滚动加载内容。这意味着一个页面所有的内容是通过你向下滚动来实现动态加载的。
这里将介绍怎么做的,你可以复制到自己网站看看效果:
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); });
检查图片是否已加载
这段代码是我使用图片时经常用到的,它是了解一个图片是否加载完毕最好的方式:
var imgsrc = 'img/image1.png'; $('<img/>').load(function () { alert('image loaded'); }).error(function () { alert('error loading image'); }).attr('src', imgsrc);
列表按字母顺序排列
在某些场景,按照字母顺序来排列一个长长的列表将非常有用,这段代码可以将任何列表按元字母顺序排序:
$(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(); });