在其他地方你學(xué)不到的jQuery小貼士和技巧(歡迎收藏)
下面小編給大家整理了8個(gè)技巧對(duì)程序員來(lái)說(shuō)非常的有幫助,具體如下所示:
1) 禁用鼠標(biāo)右鍵單擊
jQuery程序員可以使用此代碼在網(wǎng)頁(yè)上禁用鼠標(biāo)右鍵點(diǎn)擊。
$(document).ready(function() { //catch the right-click context menu $(document).bind("contextmenu",function(e) { //warning prompt - optional alert("No right-clicking!"); //delete the default context menu return false; }); });
2) 利用jQuery調(diào)整文字大小
使用此代碼,用戶可以重新網(wǎng)站上文字的大?。ㄔ龃蠛蜏p少)
$(document).ready(function() { //find the current font size var originalFontSize = $('html').css('font-size'); //Increase the text size $(".increaseFont").click(function() { var currentFontSize = $('html').css('font-size'); var currentFontSizeNumber = parseFloat(currentFontSize, 10); var newFontSize = currentFontSizeNumber*1.2; $('html').css('font-size', newFontSize); return false; }); //Decrease the Text Size $(".decreaseFont").click(function() { var currentFontSize = $('html').css('font-size'); var currentFontSizeNum = parseFloat(currentFontSize, 10); var newFontSize = currentFontSizeNum*0.8; $('html').css('font-size', newFontSize); return false; }); // Reset Font Size $(".resetFont").click(function(){ $('html').css('font-size', originalFontSize); }); });
3) 在新的Windows打開(kāi)鏈接
Try this code and increase your site impressions because using this jquery code users will go on new window after clicking on any link of your site. Code is below: -
$(document).ready(function() { //select all anchor tags that have http in the href //and apply the target=_blank $("a[href^='http']").attr('target','_blank'); });
4) Style Sheets Swap
Swap style sheets using this code and the “Style sheets swap” script is below: -
$(document).ready(function() { $("a.cssSwap").click(function() { //swap the link rel attribute with the value in the rel $('link[rel=stylesheet]').attr('href' , $(this).attr('rel')); }); });
5) 回到頂部鏈接
That is very common function you can see on eve site nowadays is ” Back to Top”. This functionality is very useful for long pages for make short in a single click. Visit this code below: -
$(document).ready(function() { //when the id="top" link is clicked $('#top').click(function() { //scoll the page back to the top $(document).scrollTo(0,500); } });
6) 獲取鼠標(biāo)光標(biāo)的x和y軸
You can find the values of X and Y coordinator of mouse pointer. Code is blow : -
$().mousemove(function(e){ //display the x and y axis values inside the P element $('p').html("X Axis : " + e.pageX + " | Y Axis " + e.pageY); });
7) 檢測(cè)當(dāng)前鼠標(biāo)坐標(biāo)
使用這個(gè)腳本,你可以在jQuery所支持的任何Web瀏覽器找到當(dāng)前鼠標(biāo)的坐標(biāo)。代碼如下:
$(document).ready(function() { $().mousemove(function(e) { $('# MouseCoordinates ').html("X Axis Position = " + e.pageX + " and Y Axis Position = " + e.pageY); }); });
8) 在jQuery中預(yù)加載圖片
此圖像預(yù)加載的腳本有助于非常快速加載圖像或網(wǎng)頁(yè)。你不必等待圖像加載。代碼:
jQuery.preloadImagesInWebPage = function() { for(var ctr = 0; ctr<arguments.length; ctr++) { jQuery("<img alt="">").attr("src", arguments[ctr]); } } To use the above method, you can use the following piece of code: $.preloadImages("image1.gif", "image2.gif", "image3.gif"); To check whether an image has been loaded, you can use the following piece of code: $('#imageObject').attr('src', 'image1.gif').load(function() { alert('The image has been loaded…'); });
做好如下工作保你jQuery的性能大提升
1. Append Outside of Loops
凡是觸及到DOM都是有代價(jià)的。如果你向DOM當(dāng)中附加大量的元素,你會(huì)想一次性將它們?nèi)扛郊舆M(jìn)來(lái),而不是分多次進(jìn)行。當(dāng)在循環(huán)當(dāng)中附加元素就會(huì)產(chǎn)生一個(gè)常見(jiàn)的問(wèn)題。
$.each( myArray, function( i, item ) { var newListItem = "<li>" + item + "</li>"; $( "#ballers" ).append( newListItem ); });
一個(gè)常用的技巧是利用文檔片段(document fragment)。在循環(huán)的每一次迭代當(dāng)中,將元素附加到片段而不是DOM元素當(dāng)中。當(dāng)循環(huán)結(jié)束后,將片段附加到DOM元素當(dāng)中即可。
var frag = document.createDocumentFragment(); $.each( myArray, function( i, item ) { var newListItem = document.createElement( "li" ); var itemText = document.createTextNode( item ); newListItem.appendChild( itemText ); frag.appendChild( newListItem ); }); $( "#ballers" )[ ].appendChild( frag );
另一個(gè)簡(jiǎn)單的技巧是在循環(huán)的每次迭代當(dāng)中,持續(xù)構(gòu)建一個(gè)字符串。當(dāng)循環(huán)結(jié)束后,將DOM元素的HTML設(shè)置成該字符串。
var myHtml = ""; $.each( myArray, function( i, item ) { myHtml += "<li>" + item + "</li>"; }); $( "#ballers" ).html( myHtml );
當(dāng)然還有其它一些技巧可以供你嘗試。一個(gè)名為 jsperf 的站點(diǎn)為測(cè)試這些性能提供了一條好的出路。該網(wǎng)站允許你使用基準(zhǔn)測(cè)試每一個(gè)技巧,并將其跨平臺(tái)的性能測(cè)試結(jié)果可視化的展現(xiàn)出來(lái)。
2. Cache Length During Loops
在for循環(huán)當(dāng)中,不要每次都訪問(wèn)數(shù)組的 length 屬性;應(yīng)當(dāng)事先將其緩存起來(lái)。
var myLength = myArray.length; for ( var i = ; i < myLength; i++ ) { // do stuff }
3. Detach Elements to Work with Them
操作DOM是緩慢的,因此你想盡可能減少對(duì)齊進(jìn)行操作。jQuery在1.4版本當(dāng)中引入了名為 detach() 的方法來(lái)幫助解決這一問(wèn)題,它允許你在對(duì)元素進(jìn)行操作時(shí),將它們從DOM當(dāng)中分離出來(lái)。
var $table = $( "#myTable" ); var $parent = $table.parent(); $table.detach(); // ... add lots and lots of rows to table $parent.append( $table );
4. Don't Act on Absent Elements
如果你正打算在一個(gè)空的選擇器上運(yùn)行大量的代碼,jQuery并不會(huì)給予任何的提示 -- 它將會(huì)繼續(xù)的執(zhí)行,就像是沒(méi)有發(fā)生任何的錯(cuò)誤。必須由你來(lái)驗(yàn)證選擇器包含了多少元素。
// Bad: This runs three functions before it // realizes there's nothing in the selection $( "#nosuchthing" ).slideUp(); // Better: var $mySelection = $( "#nosuchthing" ); if ( $mySelection.length ) { $mySelection.slideUp(); } // Best: Add a doOnce plugin. jQuery.fn.doOnce = function( func ) { this.length && func.apply( this ); return this; } $( "li.cartitems" ).doOnce(function() { // make it ajax! \o/ });
本指南特別適用于那些當(dāng)選擇器不包含元素時(shí)還需要大量的開(kāi)銷的 jQuery UI 部件。
5. Optimize Selectors
選擇器的優(yōu)化和過(guò)去比起來(lái)并不是那么的重要,因?yàn)楹芏酁g覽器都實(shí)現(xiàn)了 document.querySelectorAll() 方法并且jQuery將選擇器的負(fù)擔(dān)轉(zhuǎn)移到了瀏覽器上面。但是仍然有一些技巧需要銘記在心。
基于ID的選擇器
以一個(gè)ID作為選擇器的開(kāi)始總是最好的。
// Fast: $( "#container div.robotarm" ); // Super-fast: $( "#container" ).find( "div.robotarm" );
采用 .find() 方法的方式將更加的快速,因?yàn)榈谝粋€(gè)選擇器已經(jīng)過(guò)處理,而無(wú)需通過(guò)嘈雜的選擇器引擎 -- ID-Only的選擇器已使用 document.getElementById() 方法進(jìn)行處理,之所以快速,是因?yàn)樗菫g覽器的原生方法。
特異性
盡量詳細(xì)的描述選擇器的右側(cè),對(duì)于左側(cè)則應(yīng)反其道而行之。
// Unoptimized: $( "div.data .gonzalez" ); // Optimized: $( ".data td.gonzalez" );
盡量在選擇器的最右側(cè)使用 tag.class 的形式來(lái)描述選擇器,而在左側(cè)則盡量只使用 tag 或者 .class 。
避免過(guò)度使用特異性
$( ".data table.attendees td.gonzalez" ); // Better: Drop the middle if possible. $( ".data td.gonzalez" );
去討好“DOM”總是有利于提升選擇器的性能,因?yàn)檫x擇器引擎在搜尋元素時(shí)無(wú)需進(jìn)行太多的遍歷。
避免使用通用選擇器
如果一個(gè)選擇器明確或暗示它能在不確定的范圍內(nèi)進(jìn)行匹配將會(huì)大大影響性能。
$( ".buttons > *" ); // Extremely expensive. $( ".buttons" ).children(); // Much better. $( ".category :radio" ); // Implied universal selection. $( ".category *:radio" ); // Same thing, explicit now. $( ".category input:radio" ); // Much better.
6. Use Stylesheets for Changing CSS on Many Elements
假如你使用 .css() 方法來(lái)改變超過(guò)20個(gè)元素的CSS,應(yīng)當(dāng)考慮為頁(yè)面添加一個(gè)樣式標(biāo)簽作為替代,這樣做可以提升將近60%的速度。
// Fine for up to elements, slow after that: $( "a.swedberg" ).css( "color", "#ad" ); // Much faster: $( "<style type=\"text/css\">a.swedberg { color: #ad }</style>") .appendTo( "head" );
7. Don't Treat jQuery as a Black Box
把jQuery的源碼當(dāng)成文檔,可以把它(http://bit.ly/jqsource)保存在你的收藏夾內(nèi),經(jīng)常的查閱參考。
- JQuery Tips(4) 一些關(guān)于提高JQuery性能的Tips
- jquery 1.4.2發(fā)布!主要是性能與API
- Jquery優(yōu)化效率 提升性能解決方案
- 打造基于jQuery的高性能TreeView(asp.net)
- JQuery each()函數(shù)如何優(yōu)化循環(huán)DOM結(jié)構(gòu)的性能
- 十個(gè)迅速提升JQuery性能讓你的JQuery跑得更快
- jquery選擇器的選擇使用及性能介紹
- js的壓縮及jquery壓縮探討(提高頁(yè)面加載性能/保護(hù)勞動(dòng)成果)
- JQuery for與each性能比較分析
- 如何書(shū)寫(xiě)高質(zhì)量jQuery代碼(使用jquery性能問(wèn)題)
- jQuery性能優(yōu)化技巧分析
- 提高jQuery性能優(yōu)化的技巧
- jquery性能優(yōu)化高級(jí)技巧
相關(guān)文章
jQuery操作動(dòng)態(tài)生成的內(nèi)容的方法
這篇文章主要介紹了jQuery操作動(dòng)態(tài)生成的內(nèi)容的方法,對(duì)比分析了bind與live方法,說(shuō)明了live方法在處理新增元素時(shí)的作用,需要的朋友可以參考下2016-05-05jQuery實(shí)現(xiàn)可兼容IE6的淡入淡出效果告警提示功能示例
這篇文章主要介紹了jQuery實(shí)現(xiàn)可兼容IE6的淡入淡出效果告警提示功能,結(jié)合具體實(shí)例形式分析了jQuery彈出警告提示功能的具體實(shí)現(xiàn)步驟與相關(guān)操作技巧,需要的朋友可以參考下2017-09-09基于jQuery的上下無(wú)縫滾動(dòng)應(yīng)用(單行或多行)
基于jQuery的上下無(wú)縫滾動(dòng)應(yīng)用,可應(yīng)用于多行或者單行.詳解請(qǐng)參考注釋.2010-08-08Eclipse引入jquery報(bào)錯(cuò)如何解決
有朋友問(wèn)我,在是使用eclipse的過(guò)程中遇到了這么一個(gè)問(wèn)題--eclipse導(dǎo)入jquery包后報(bào)錯(cuò)——究竟是什么原因?qū)е逻@一問(wèn)題發(fā)生的呢?該如何解決此問(wèn)題呢?下面小編給大家?guī)?lái)了解決辦法,不妨一起看看吧2015-12-12checkbox批量選中,獲取選中項(xiàng)的值的簡(jiǎn)單實(shí)例
下面小編就為大家?guī)?lái)一篇checkbox批量選中,獲取選中項(xiàng)的值的簡(jiǎn)單實(shí)例。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2016-06-06