每一個程序員都會的 35 個 jQuery 小技巧

  1 收集的35個 jQuery 小技巧/代碼片斷,能夠幫你快速開發.
  2 1. 禁止右鍵點擊
  3 $(document).ready(function(){
  4     $(document).bind("contextmenu",function(e){
  5         return false;
  6     });
  7 });
  8 2. 隱藏搜索文本框文字
  9 Hide when clicked in the search field, the value.(example can be found below in the comment fields)
 10 
 11 $(document).ready(function() {
 12 $("input.text1").val("Enter your search text here");
 13    textFill($('input.text1'));
 14 });
 15 
 16     function textFill(input){ //input focus text function
 17      var originalvalue = input.val();
 18      input.focus( function(){
 19           if( $.trim(input.val()) == originalvalue ){ input.val(''); }
 20      });
 21      input.blur( function(){
 22           if( $.trim(input.val()) == '' ){ input.val(originalvalue); }
 23      });
 24 }
 25 3. 在新窗口中打開連接
 26 XHTML 1.0 Strict doesn’t allow this attribute in the code, so use this to keep the code valid.
 27 
 28 $(document).ready(function() {
 29    //Example 1: Every link will open in a new window
 30    $('a[href^="http://"]').attr("target", "_blank");
 31 
 32    //Example 2: Links with the rel="external" attribute will only open in a new window
 33    $('a[@rel$='external']').click(function(){
 34       this.target = "_blank";
 35    });
 36 });
 37 // how to use
 38 <a href="http://www.opensourcehunter.com" rel=external>open link</a>
 39 4. 檢測瀏覽器
 40 注: 在版本jQuery 1.4中,$.support 替換掉了$.browser 變量
 41 $(document).ready(function() {
 42 // Target Firefox 2 and above
 43 if ($.browser.mozilla && $.browser.version >= "1.8" ){
 44     // do something
 45 }
 46 
 47 // Target Safari
 48 if( $.browser.safari ){
 49     // do something
 50 }
 51 
 52 // Target Chrome
 53 if( $.browser.chrome){
 54     // do something
 55 }
 56 
 57 // Target Camino
 58 if( $.browser.camino){
 59     // do something
 60 }
 61 
 62 // Target Opera
 63 if( $.browser.opera){
 64     // do something
 65 }
 66 
 67 // Target IE6 and below
 68 if ($.browser.msie && $.browser.version <= 6 ){
 69     // do something
 70 }
 71 
 72 // Target anything above IE6
 73 if ($.browser.msie && $.browser.version > 6){
 74     // do something
 75 }
 76 });
 77 5. 預加載圖片
 78 This piece of code will prevent the loading of all images, which can be useful if you have a site with lots of images.
 79 $(document).ready(function() {
 80 jQuery.preloadImages = function()
 81 {
 82   for(var i = 0; i<ARGUMENTS.LENGTH; jQuery(?<img { i++)>").attr("src", arguments[i]);
 83   }
 84 }
 85 // how to use
 86 $.preloadImages("image1.jpg");
 87 });
 88 6. 頁面樣式切換
 89 $(document).ready(function() {
 90     $("a.Styleswitcher").click(function() {
 91         //swicth the LINK REL attribute with the value in A REL attribute
 92         $('link[rel=stylesheet]').attr('href' , $(this).attr('rel'));
 93     });
 94 // how to use
 95 // place this in your header
 96 <LINK rel=stylesheet type=text/css href="default.css">
 97 // the links
 98 <A href="#" rel=default.css>Default Theme</A>
 99 <A href="#" rel=red.css>Red Theme</A>
100 <A href="#" rel=blue.css>Blue Theme</A>
101 });
102 7. 列高度相同
103 若是使用了兩個CSS列,使用此種方式能夠是兩列的高度相同。
104 $(document).ready(function() {
105 function equalHeight(group) {
106     tallest = 0;
107     group.each(function() {
108         thisHeight = $(this).height();
109         if(thisHeight > tallest) {
110             tallest = thisHeight;
111         }
112     });
113     group.height(tallest);
114 }
115 // how to use
116 $(document).ready(function() {
117     equalHeight($(".left"));
118     equalHeight($(".right"));
119 });
120 });
121 8. 動態控制頁面字體大小
122 用戶能夠改變頁面字體大小
123 $(document).ready(function() {
124   // Reset the font size(back to default)
125   var originalFontSize = $('html').css('font-size');
126     $(".resetFont").click(function(){
127     $('html').css('font-size', originalFontSize);
128   });
129   // Increase the font size(bigger font0
130   $(".increaseFont").click(function(){
131     var currentFontSize = $('html').css('font-size');
132     var currentFontSizeNum = parseFloat(currentFontSize, 10);
133     var newFontSize = currentFontSizeNum*1.2;
134     $('html').css('font-size', newFontSize);
135     return false;
136   });
137   // Decrease the font size(smaller font)
138   $(".decreaseFont").click(function(){
139     var currentFontSize = $('html').css('font-size');
140     var currentFontSizeNum = parseFloat(currentFontSize, 10);
141     var newFontSize = currentFontSizeNum*0.8;
142     $('html').css('font-size', newFontSize);
143     return false;
144   });
145 });
146 9. 返回頁面頂部功能
147 For a smooth(animated) ride back to the top(or any location).
148 $(document).ready(function() {
149 $('a[href*=#]').click(function() {
150  if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
151  && location.hostname == this.hostname) {
152    var $target = $(this.hash);
153    $target = $target.length && $target
154    || $('[name=' + this.hash.slice(1) +']');
155    if ($target.length) {
156   var targetOffset = $target.offset().top;
157   $('html,body')
158   .animate({scrollTop: targetOffset}, 900);
159     return false;
160    }
161   }
162   });
163 // how to use
164 // place this where you want to scroll to
165 <A name=top></A>
166 // the link
167 <A href="#top">go to top</A>
168 });
169 10. 得到鼠標指針XY值
170 Want to know where your mouse cursor is?
171 $(document).ready(function() {
172    $().mousemove(function(e){
173      //display the x and y axis values inside the div with the id XY
174     $('#XY').html("X Axis : " + e.pageX + " | Y Axis " + e.pageY);
175   });
176 // how to use
177 <DIV id=XY></DIV>
178 
179 });
180 11.返回頂部按鈕
181 你能夠利用 animate 和 scrollTop 來實現返回頂部的動畫,而不須要使用其餘插件。
182 // Back to top
183 $('a.top').click(function () {
184   $(document.body).animate({scrollTop: 0}, 800);
185   return false;
186 });
187 <!-- Create an anchor tag -->
188 <a href="#">Back to top</a>
189 改變 scrollTop 的值能夠調整返回距離頂部的距離,而 animate 的第二個參數是執行返回動做須要的時間(單位:毫秒)。
190 12.預加載圖片
191 若是你的頁面中使用了不少不可見的圖片(如:hover 顯示),你可能須要預加載它們:
192 $.preloadImages = function () {
193   for (var i = 0; i < arguments.length; i++) {
194     $('<img>').attr('src', arguments[i]);
195   }
196 };
197 
198 $.preloadImages('img/hover1.png', 'img/hover2.png');
199 13.檢查圖片是否加載完成
200 有時候你須要確保圖片完成加載完成以便執行後面的操做:
201 $('img').load(function () {
202   console.log('image load successful');
203 });
204 你能夠把 img 替換爲其餘的 ID 或者 class 來檢查指定圖片是否加載完成。
205 14.自動修改破損圖像
206 若是你碰巧在你的網站上發現了破碎的圖像連接,你能夠用一個不易被替換的圖像來代替它們。添加這個簡單的代碼能夠節省不少麻煩:
207 $('img').on('error', function () {
208   $(this).prop('src', 'img/broken.png');
209 });
210 即便你的網站沒有破碎的圖像連接,添加這段代碼也沒有任何害處。
211 15.鼠標懸停(hover)切換 class 屬性
212 假如當用戶鼠標懸停在一個可點擊的元素上時,你但願改變其效果,下面這段代碼能夠在其懸停在元素上時添加 class 屬性,當用戶鼠標離開時,則自動取消該 class 屬性:
213 $('.btn').hover(function () {
214   $(this).addClass('hover');
215   }, function () {
216     $(this).removeClass('hover');
217   });
218 你只須要添加必要的CSS代碼便可。若是你想要更簡潔的代碼,可使用 toggleClass 方法:
219 $('.btn').hover(function () { 
220   $(this).toggleClass('hover'); 
221 });
222 注:直接使用CSS實現該效果多是更好的解決方案,但你仍然有必要知道該方法。
223 16.禁用 input 字段
224 有時你可能須要禁用表單的 submit 按鈕或者某個 input 字段,直到用戶執行了某些操做(例如,檢查「已閱讀條款」複選框)。能夠添加 disabled 屬性,直到你想啓用它時:
225 $('input[type="submit"]').prop('disabled', true);
226 你要作的就是執行 removeAttr 方法,並把要移除的屬性做爲參數傳入:
227 $('input[type="submit"]').removeAttr('disabled');
228 17.阻止連接加載
229 有時你不但願連接到某個頁面或者從新加載它,你可能但願它來作一些其餘事情或者觸發一些其餘腳本,你能夠這麼作:
230 $('a.no-link').click(function (e) {
231   e.preventDefault();
232 });
233 18.切換 fade/slide
234 fade 和 slide 是咱們在 jQuery 中常常使用的動畫效果,它們可使元素顯示效果更好。可是若是你但願元素顯示時使用第一種效果,而消失時使用第二種效果,則能夠這麼作:
235 // Fade
236 $('.btn').click(function () {
237   $('.element').fadeToggle('slow');
238 });
239 // Toggle
240 $('.btn').click(function () {
241   $('.element').slideToggle('slow');
242 });
243 19.簡單的手風琴效果
244 這是一個實現手風琴效果快速簡單的方法:
245 // Close all panels
246 $('#accordion').find('.content').hide();
247 // Accordion
248 $('#accordion').find('.accordion-header').click(function () {
249   var next = $(this).next();
250   next.slideToggle('fast');
251   $('.content').not(next).slideUp('fast');
252   return false;
253 });
254 20.讓兩個 DIV 高度相同
255 有時你須要讓兩個 div 高度相同,而無論它們裏面的內容多少。可使用下面的代碼片斷:
256 var $columns = $('.column');
257 var height = 0;
258 $columns.each(function () {
259   if ($(this).height() > height) {
260     height = $(this).height();
261   }
262 });
263 $columns.height(height);
264 這段代碼會循環一組元素,並設置它們的高度爲元素中的最大高。
265 21. 驗證元素是否爲空
266 This will allow you to check if an element is empty.
267 $(document).ready(function() {
268   if ($('#id').html()) {
269    // do something
270    }
271 });
272 22. 替換元素
273 $(document).ready(function() {
274    $('#id').replaceWith('
275 <DIV>I have been replaced</DIV>
276 
277 ');
278 });
279 23. jQuery延時加載功能
280 $(document).ready(function() {
281    window.setTimeout(function() {
282      // do something
283    }, 1000);
284 });
285 24. 移除單詞功能
286 $(document).ready(function() {
287    var el = $('#id');
288    el.html(el.html().replace(/word/ig, ""));
289 });
290 25. 驗證元素是否存在於jquery對象集合中
291 $(document).ready(function() {
292    if ($('#id').length) {
293   // do something
294   }
295 });
296 26. 使整個DIV可點擊
297 $(document).ready(function() {
298     $("div").click(function(){
299       //get the url from href attribute and launch the url
300       window.location=$(this).find("a").attr("href"); return false;
301     });
302 // how to use
303 <DIV><A href="index.html">home</A></DIV>
304 
305 });
306 27. ID與Class之間轉換
307 當改變Window大小時,在ID與Class之間切換
308 $(document).ready(function() {
309    function checkWindowSize() {
310     if ( $(window).width() > 1200 ) {
311         $('body').addClass('large');
312     }
313     else {
314         $('body').removeClass('large');
315     }
316    }
317 $(window).resize(checkWindowSize);
318 });
319 28. 克隆對象
320 $(document).ready(function() {
321    var cloned = $('#id').clone();
322 // how to use
323 <DIV id=id></DIV>
324 
325 });
326 29. 使元素居屏幕中間位置
327 $(document).ready(function() {
328   jQuery.fn.center = function () {
329       this.css("position","absolute");
330       this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");
331       this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");
332       return this;
333   }
334   $("#id").center();
335 });
336 30. 寫本身的選擇器
337 $(document).ready(function() {
338    $.extend($.expr[':'], {
339        moreThen1000px: function(a) {
340            return $(a).width() > 1000;
341       }
342    });
343   $('.box:moreThen1000px').click(function() {
344       // creating a simple js alert box
345       alert('The element that you have clicked is over 1000 pixels wide');
346   });
347 });
348 31. 統計元素個數
349 $(document).ready(function() {
350    $("p").size();
351 });
352 32. 使用本身的 Bullets
353 $(document).ready(function() {
354    $("ul").addClass("Replaced");
355    $("ul > li").prepend("? ");
356  // how to use
357  ul.Replaced { list-style : none; }
358 });
359 33. 引用Google主機上的Jquery類庫
360 //Example 1
361 <SCRIPT src="http://www.google.com/jsapi"></SCRIPT>
362 <SCRIPT type=text/javascript>
363 google.load("jquery", "1.2.6");
364 google.setOnLoadCallback(function() {
365     // do something
366 });
367 </SCRIPT><SCRIPT type=text/javascript src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></SCRIPT>
368 
369  // Example 2:(the best and fastest way)
370 <SCRIPT type=text/javascript src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></SCRIPT>
371 34. 禁用Jquery(動畫)效果
372 $(document).ready(function() {
373     jQuery.fx.off = true;
374 });
375 35. 與其餘Javascript類庫衝突解決方案
376 $(document).ready(function() {
377    var $jq = jQuery.noConflict();
378    $jq('#id').show();
379 });
相關文章
相關標籤/搜索