下面小編給大家整理了8個技巧對程序員來說非常的有幫助,具體如下所示:
1) 禁用鼠標右鍵單擊
jQuery程序員可以使用此代碼在網頁上禁用鼠標右鍵點擊。
$(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調整文字大小
使用此代碼,用戶可以重新網站上文字的大小(增大和減少)
$(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) 獲取鼠標光標的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) 檢測當前鼠標坐標
使用這個腳本,你可以在jQuery所支持的任何Web瀏覽器找到當前鼠標的坐標。代碼如下:
$(document).ready(function() { $().mousemove(function(e) { $('# MouseCoordinates ').html("X Axis Position = " + e.pageX + " and Y Axis Position = " + e.pageY); }); });
8) 在jQuery中預加載圖片
此圖像預加載的腳本有助于非常快速加載圖像或網頁。你不必等待圖像加載。代碼:
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當中附加大量的元素,你會想一次性將它們全部附加進來,而不是分多次進行。當在循環當中附加元素就會產生一個常見的問題。
$.each( myArray, function( i, item ) { var newListItem = "<li>" + item + "</li>"; $( "#ballers" ).append( newListItem ); });
一個常用的技巧是利用文檔片段(document fragment)。在循環的每一次迭代當中,將元素附加到片段而不是DOM元素當中。當循環結束后,將片段附加到DOM元素當中即可。
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 );
另一個簡單的技巧是在循環的每次迭代當中,持續構建一個字符串。當循環結束后,將DOM元素的HTML設置成該字符串。
var myHtml = ""; $.each( myArray, function( i, item ) { myHtml += "<li>" + item + "</li>"; }); $( "#ballers" ).html( myHtml );
當然還有其它一些技巧可以供你嘗試。一個名為 jsperf 的站點為測試這些性能提供了一條好的出路。該網站允許你使用基準測試每一個技巧,并將其跨平臺的性能測試結果可視化的展現出來。
2. Cache Length During Loops
在for循環當中,不要每次都訪問數組的 length 屬性;應當事先將其緩存起來。
var myLength = myArray.length; for ( var i = ; i < myLength; i++ ) { // do stuff }
3. Detach Elements to Work with Them
操作DOM是緩慢的,因此你想盡可能減少對齊進行操作。jQuery在1.4版本當中引入了名為 detach() 的方法來幫助解決這一問題,它允許你在對元素進行操作時,將它們從DOM當中分離出來。
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并不會給予任何的提示 -- 它將會繼續的執行,就像是沒有發生任何的錯誤。必須由你來驗證選擇器包含了多少元素。
// 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/ });
本指南特別適用于那些當選擇器不包含元素時還需要大量的開銷的 jQuery UI 部件。
5. Optimize Selectors
選擇器的優化和過去比起來并不是那么的重要,因為很多瀏覽器都實現了 document.querySelectorAll() 方法并且jQuery將選擇器的負擔轉移到了瀏覽器上面。但是仍然有一些技巧需要銘記在心。
基于ID的選擇器
以一個ID作為選擇器的開始總是最好的。
// Fast: $( "#container div.robotarm" ); // Super-fast: $( "#container" ).find( "div.robotarm" );
采用 .find() 方法的方式將更加的快速,因為第一個選擇器已經過處理,而無需通過嘈雜的選擇器引擎 -- ID-Only的選擇器已使用 document.getElementById() 方法進行處理,之所以快速,是因為它是瀏覽器的原生方法。
特異性
盡量詳細的描述選擇器的右側,對于左側則應反其道而行之。
// Unoptimized: $( "div.data .gonzalez" ); // Optimized: $( ".data td.gonzalez" );
盡量在選擇器的最右側使用 tag.class 的形式來描述選擇器,而在左側則盡量只使用 tag 或者 .class 。
避免過度使用特異性
$( ".data table.attendees td.gonzalez" ); // Better: Drop the middle if possible. $( ".data td.gonzalez" );
去討好“DOM”總是有利于提升選擇器的性能,因為選擇器引擎在搜尋元素時無需進行太多的遍歷。
避免使用通用選擇器
如果一個選擇器明確或暗示它能在不確定的范圍內進行匹配將會大大影響性能。
$( ".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,應當考慮為頁面添加一個樣式標簽作為替代,這樣做可以提升將近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的源碼當成文檔,可以把它(http://bit.ly/jqsource)保存在你的收藏夾內,經常的查閱參考。