在其他地方你学不到的jQuery小贴士和技巧(欢迎收藏)
下面小编给大家整理了8个技巧对程序员来说非常的有帮助,具体如下所示:
1)禁用鼠标右键单击
jQuery程序员可以使用此代码在网页上禁用鼠标右键点击。
$(document).ready(function(){ //catchtheright-clickcontextmenu $(document).bind("contextmenu",function(e){ //warningprompt-optional alert("Noright-clicking!"); //deletethedefaultcontextmenu returnfalse; }); });
2)利用jQuery调整文字大小
使用此代码,用户可以重新网站上文字的大小(增大和减少)
$(document).ready(function(){ //findthecurrentfontsize varoriginalFontSize=$('html').css('font-size'); //Increasethetextsize $(".increaseFont").click(function(){ varcurrentFontSize=$('html').css('font-size'); varcurrentFontSizeNumber=parseFloat(currentFontSize,10); varnewFontSize=currentFontSizeNumber*1.2; $('html').css('font-size',newFontSize); returnfalse; }); //DecreasetheTextSize $(".decreaseFont").click(function(){ varcurrentFontSize=$('html').css('font-size'); varcurrentFontSizeNum=parseFloat(currentFontSize,10); varnewFontSize=currentFontSizeNum*0.8; $('html').css('font-size',newFontSize); returnfalse; }); //ResetFontSize $(".resetFont").click(function(){ $('html').css('font-size',originalFontSize); }); });
3)在新的Windows打开链接
Trythiscodeandincreaseyoursiteimpressionsbecauseusingthisjquerycodeuserswillgoonnewwindowafterclickingonanylinkofyoursite.Codeisbelow:-
$(document).ready(function(){ //selectallanchortagsthathavehttpinthehref //andapplythetarget=_blank $("a[href^='http']").attr('target','_blank'); });
4)StyleSheetsSwap
Swapstylesheetsusingthiscodeandthe“Stylesheetsswap”scriptisbelow:-
$(document).ready(function(){ $("a.cssSwap").click(function(){ //swapthelinkrelattributewiththevalueintherel $('link[rel=stylesheet]').attr('href',$(this).attr('rel')); }); });
5)回到顶部链接
Thatisverycommonfunctionyoucanseeonevesitenowadaysis”BacktoTop”.Thisfunctionalityisveryusefulforlongpagesformakeshortinasingleclick.Visitthiscodebelow:-
$(document).ready(function(){ //whentheid="top"linkisclicked $('#top').click(function(){ //scollthepagebacktothetop $(document).scrollTo(0,500); } });
6)获取鼠标光标的x和y轴
YoucanfindthevaluesofXandYcoordinatorofmousepointer.Codeisblow:-
$().mousemove(function(e){ //displaythexandyaxisvaluesinsidethePelement $('p').html("XAxis:"+e.pageX+"|YAxis"+e.pageY); });
7)检测当前鼠标坐标
使用这个脚本,你可以在jQuery所支持的任何Web浏览器找到当前鼠标的坐标。代码如下:
$(document).ready(function(){ $().mousemove(function(e) { $('#MouseCoordinates').html("XAxisPosition="+e.pageX+"andYAxisPosition="+e.pageY); }); });
8)在jQuery中预加载图片
此图像预加载的脚本有助于非常快速加载图像或网页。你不必等待图像加载。代码:
jQuery.preloadImagesInWebPage=function() { for(varctr=0;ctr<arguments.length;ctr++) { jQuery("<imgalt="">").attr("src",arguments[ctr]); } } Tousetheabovemethod,youcanusethefollowingpieceofcode: $.preloadImages("image1.gif","image2.gif","image3.gif"); Tocheckwhetheranimagehasbeenloaded,youcanusethefollowingpieceofcode: $('#imageObject').attr('src','image1.gif').load(function(){ alert('Theimagehasbeenloaded…'); });
做好如下工作保你jQuery的性能大提升
1.AppendOutsideofLoops
凡是触及到DOM都是有代价的。如果你向DOM当中附加大量的元素,你会想一次性将它们全部附加进来,而不是分多次进行。当在循环当中附加元素就会产生一个常见的问题。
$.each(myArray,function(i,item){ varnewListItem="<li>"+item+"</li>"; $("#ballers").append(newListItem); });
一个常用的技巧是利用文档片段(documentfragment)。在循环的每一次迭代当中,将元素附加到片段而不是DOM元素当中。当循环结束后,将片段附加到DOM元素当中即可。
varfrag=document.createDocumentFragment(); $.each(myArray,function(i,item){ varnewListItem=document.createElement("li"); varitemText=document.createTextNode(item); newListItem.appendChild(itemText); frag.appendChild(newListItem); }); $("#ballers")[].appendChild(frag);
另一个简单的技巧是在循环的每次迭代当中,持续构建一个字符串。当循环结束后,将DOM元素的HTML设置成该字符串。
varmyHtml=""; $.each(myArray,function(i,item){ myHtml+="<li>"+item+"</li>"; }); $("#ballers").html(myHtml);
当然还有其它一些技巧可以供你尝试。一个名为jsperf的站点为测试这些性能提供了一条好的出路。该网站允许你使用基准测试每一个技巧,并将其跨平台的性能测试结果可视化的展现出来。
2.CacheLengthDuringLoops
在for循环当中,不要每次都访问数组的length属性;应当事先将其缓存起来。
varmyLength=myArray.length; for(vari=;i<myLength;i++){ //dostuff }
3.DetachElementstoWorkwithThem
操作DOM是缓慢的,因此你想尽可能减少对齐进行操作。jQuery在1.4版本当中引入了名为detach()的方法来帮助解决这一问题,它允许你在对元素进行操作时,将它们从DOM当中分离出来。
var$table=$("#myTable"); var$parent=$table.parent(); $table.detach(); //...addlotsandlotsofrowstotable $parent.append($table);
4.Don'tActonAbsentElements
如果你正打算在一个空的选择器上运行大量的代码,jQuery并不会给予任何的提示--它将会继续的执行,就像是没有发生任何的错误。必须由你来验证选择器包含了多少元素。
//Bad:Thisrunsthreefunctionsbeforeit //realizesthere'snothingintheselection $("#nosuchthing").slideUp(); //Better: var$mySelection=$("#nosuchthing"); if($mySelection.length){ $mySelection.slideUp(); } //Best:AddadoOnceplugin. jQuery.fn.doOnce=function(func){ this.length&&func.apply(this); returnthis; } $("li.cartitems").doOnce(function(){ //makeitajax!\o/ });
本指南特别适用于那些当选择器不包含元素时还需要大量的开销的jQueryUI部件。
5.OptimizeSelectors
选择器的优化和过去比起来并不是那么的重要,因为很多浏览器都实现了document.querySelectorAll()方法并且jQuery将选择器的负担转移到了浏览器上面。但是仍然有一些技巧需要铭记在心。
基于ID的选择器
以一个ID作为选择器的开始总是最好的。
//Fast: $("#containerdiv.robotarm"); //Super-fast: $("#container").find("div.robotarm");
采用.find()方法的方式将更加的快速,因为第一个选择器已经过处理,而无需通过嘈杂的选择器引擎--ID-Only的选择器已使用document.getElementById()方法进行处理,之所以快速,是因为它是浏览器的原生方法。
特异性
尽量详细的描述选择器的右侧,对于左侧则应反其道而行之。
//Unoptimized: $("div.data.gonzalez"); //Optimized: $(".datatd.gonzalez");
尽量在选择器的最右侧使用tag.class的形式来描述选择器,而在左侧则尽量只使用tag或者.class。
避免过度使用特异性
$(".datatable.attendeestd.gonzalez"); //Better:Dropthemiddleifpossible. $(".datatd.gonzalez");
去讨好“DOM”总是有利于提升选择器的性能,因为选择器引擎在搜寻元素时无需进行太多的遍历。
避免使用通用选择器
如果一个选择器明确或暗示它能在不确定的范围内进行匹配将会大大影响性能。
$(".buttons>*");//Extremelyexpensive. $(".buttons").children();//Muchbetter. $(".category:radio");//Implieduniversalselection. $(".category*:radio");//Samething,explicitnow. $(".categoryinput:radio");//Muchbetter.
6.UseStylesheetsforChangingCSSonManyElements
假如你使用.css()方法来改变超过20个元素的CSS,应当考虑为页面添加一个样式标签作为替代,这样做可以提升将近60%的速度。
//Fineforuptoelements,slowafterthat: $("a.swedberg").css("color","#ad"); //Muchfaster: $("<styletype=\"text/css\">a.swedberg{color:#ad}</style>") .appendTo("head");
7.Don'tTreatjQueryasaBlackBox
把jQuery的源码当成文档,可以把它(http://bit.ly/jqsource)保存在你的收藏夹内,经常的查阅参考。