10个很棒的jQuery代码片段
图片预加载
(function($){
varcache=[];
//Argumentsareimagepathsrelativetothecurrentpage.
$.preLoadImages=function(){
varargs_len=arguments.length;
for(vari=args_len;i--;){
varcacheImage=document.createElement('img');
cacheImage.src=arguments[i];
cache.push(cacheImage);
}
}
jQuery.preLoadImages("image1.gif","/path/to/image2.png");
在新窗口打开链接(target=”blank”)
$('a[@rel$='external']').click(function(){
this.target="_blank";
});
/*
Usage:
<ahref="http://www.catswhocode.com"rel="external">catswhocode.com</a>
*/
当支持JavaScript时为body增加class
/*该代码只有1行,但是最简单的用来检测浏览器是否支持JavaScript的方法,如果支持JavaScript就在body元素增加一个hasJS的class*/
$('body').addClass('hasJS');
平滑滚动页面到某个锚点
$(document).ready(function(){
$("a.topLink").click(function(){
$("html,body").animate({
scrollTop:$($(this).attr("href")).offset().top+"px"
},{
duration:500,
easing:"swing"
});
returnfalse;
});
});
鼠标滑动时的渐入和渐出
$(document).ready(function(){
$(".thumbsimg").fadeTo("slow",0.6);//Thissetstheopacityofthethumbstofadedownto60%whenthepageloads
$(".thumbsimg").hover(function(){
$(this).fadeTo("slow",1.0);//Thisshouldsettheopacityto100%onhover
},function(){
$(this).fadeTo("slow",0.6);//Thisshouldsettheopacitybackto60%onmouseout
});
});
制作等高的列
varmax_height=0;
$("div.col").each(function(){
if($(this).height()>max_height){max_height=$(this).height();}
});
$("div.col").height(max_height);
在一些老的浏览器上启用HTML5的支持
(function(){
if(!/*@cc_on!@*/0)
return;
vare="abbr,article,aside,audio,bb,canvas,datagrid,datalist,details,dialog,eventsource,figure,footer,header,hgroup,mark,menu,meter,nav,output,progress,section,time,video".split(','),i=e.length;while(i--){document.createElement(e[i])}
})()
//然后在head中引入该js
<!--[ifltIE9]>
<scriptsrc="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
测试浏览器是否支持某些CSS3属性
varsupports=(function(){
vardiv=document.createElement('div'),
vendors='KhtmlMsOMozWebkit'.split(''),
len=vendors.length;
returnfunction(prop){
if(propindiv.style)returntrue;
prop=prop.replace(/^[a-z]/,function(val){
returnval.toUpperCase();
});
while(len--){
if(vendors[len]+propindiv.style){
//browsersupportsbox-shadow.Dowhatyouneed.
//Oruseabang(!)totestifthebrowserdoesn't.
returntrue;
}
}
returnfalse;
};
})();
if(supports('textShadow')){
document.documentElement.className+='textShadow';
获取URL中传递的参数
$.urlParam=function(name){
varresults=newRegExp('[\\?&]'+name+'=([^&#]*)').exec(window.location.href);
if(!results){return0;}
returnresults[1]||0;
}
禁用表单的回车键提交
$("#form").keypress(function(e){
if(e.which==13){
returnfalse;
}
});
之前的《直接拿来用的15个jQuery代码片段》文章就很不错,不知道大家收藏了吗?现在再来一份,一样很棒!