在其他地方你學(xué)不到的jQuery小貼士和技巧(歡迎收藏)
下面小編給大家整理了8個技巧對程序員來說非常的有幫助,具體如下所示:
1) 禁用鼠標(biāo)右鍵單擊
jQuery程序員可以使用此代碼在網(wǎng)頁上禁用鼠標(biāo)右鍵點擊。
$(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)站上文字的大小(增大和減少)
$(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打開鏈接
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) 檢測當(dāng)前鼠標(biāo)坐標(biāo)
使用這個腳本,你可以在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ù)加載的腳本有助于非??焖偌虞d圖像或網(wǎng)頁。你不必等待圖像加載。代碼:
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都是有代價的。如果你向DOM當(dāng)中附加大量的元素,你會想一次性將它們?nèi)扛郊舆M(jìn)來,而不是分多次進(jìn)行。當(dāng)在循環(huán)當(dāng)中附加元素就會產(chǎn)生一個常見的問題。
$.each( myArray, function( i, item ) { var newListItem = "<li>" + item + "</li>"; $( "#ballers" ).append( newListItem ); });
一個常用的技巧是利用文檔片段(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 );
另一個簡單的技巧是在循環(huán)的每次迭代當(dāng)中,持續(xù)構(gòu)建一個字符串。當(dāng)循環(huán)結(jié)束后,將DOM元素的HTML設(shè)置成該字符串。
var myHtml = ""; $.each( myArray, function( i, item ) { myHtml += "<li>" + item + "</li>"; }); $( "#ballers" ).html( myHtml );
當(dāng)然還有其它一些技巧可以供你嘗試。一個名為 jsperf 的站點為測試這些性能提供了一條好的出路。該網(wǎng)站允許你使用基準(zhǔn)測試每一個技巧,并將其跨平臺的性能測試結(jié)果可視化的展現(xiàn)出來。
2. Cache Length During Loops
在for循環(huán)當(dāng)中,不要每次都訪問數(shù)組的 length 屬性;應(yīng)當(dāng)事先將其緩存起來。
var myLength = myArray.length; for ( var i = ; i < myLength; i++ ) { // do stuff }
3. Detach Elements to Work with Them
操作DOM是緩慢的,因此你想盡可能減少對齊進(jìn)行操作。jQuery在1.4版本當(dāng)中引入了名為 detach() 的方法來幫助解決這一問題,它允許你在對元素進(jìn)行操作時,將它們從DOM當(dāng)中分離出來。
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
如果你正打算在一個空的選擇器上運行大量的代碼,jQuery并不會給予任何的提示 -- 它將會繼續(xù)的執(zhí)行,就像是沒有發(fā)生任何的錯誤。必須由你來驗證選擇器包含了多少元素。
// 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)選擇器不包含元素時還需要大量的開銷的 jQuery UI 部件。
5. Optimize Selectors
選擇器的優(yōu)化和過去比起來并不是那么的重要,因為很多瀏覽器都實現(xiàn)了 document.querySelectorAll() 方法并且jQuery將選擇器的負(fù)擔(dān)轉(zhuǎn)移到了瀏覽器上面。但是仍然有一些技巧需要銘記在心。
基于ID的選擇器
以一個ID作為選擇器的開始總是最好的。
// Fast: $( "#container div.robotarm" ); // Super-fast: $( "#container" ).find( "div.robotarm" );
采用 .find() 方法的方式將更加的快速,因為第一個選擇器已經(jīng)過處理,而無需通過嘈雜的選擇器引擎 -- ID-Only的選擇器已使用 document.getElementById() 方法進(jìn)行處理,之所以快速,是因為它是瀏覽器的原生方法。
特異性
盡量詳細(xì)的描述選擇器的右側(cè),對于左側(cè)則應(yīng)反其道而行之。
// Unoptimized: $( "div.data .gonzalez" ); // Optimized: $( ".data td.gonzalez" );
盡量在選擇器的最右側(cè)使用 tag.class 的形式來描述選擇器,而在左側(cè)則盡量只使用 tag 或者 .class 。
避免過度使用特異性
$( ".data table.attendees td.gonzalez" ); // Better: Drop the middle if possible. $( ".data td.gonzalez" );
去討好“DOM”總是有利于提升選擇器的性能,因為選擇器引擎在搜尋元素時無需進(jìn)行太多的遍歷。
避免使用通用選擇器
如果一個選擇器明確或暗示它能在不確定的范圍內(nèi)進(jìn)行匹配將會大大影響性能。
$( ".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() 方法來改變超過20個元素的CSS,應(yīng)當(dāng)考慮為頁面添加一個樣式標(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)的性能
- 十個迅速提升JQuery性能讓你的JQuery跑得更快
- jquery選擇器的選擇使用及性能介紹
- js的壓縮及jquery壓縮探討(提高頁面加載性能/保護(hù)勞動成果)
- JQuery for與each性能比較分析
- 如何書寫高質(zhì)量jQuery代碼(使用jquery性能問題)
- jQuery性能優(yōu)化技巧分析
- 提高jQuery性能優(yōu)化的技巧
- jquery性能優(yōu)化高級技巧
相關(guān)文章
jQuery實現(xiàn)可兼容IE6的淡入淡出效果告警提示功能示例
這篇文章主要介紹了jQuery實現(xiàn)可兼容IE6的淡入淡出效果告警提示功能,結(jié)合具體實例形式分析了jQuery彈出警告提示功能的具體實現(xiàn)步驟與相關(guān)操作技巧,需要的朋友可以參考下2017-09-09基于jQuery的上下無縫滾動應(yīng)用(單行或多行)
基于jQuery的上下無縫滾動應(yīng)用,可應(yīng)用于多行或者單行.詳解請參考注釋.2010-08-08