JQuery小技巧

 

1. 禁止右鍵點擊

$(document).ready(function(){ $(document).bind("contextmenu",function(e){ return false; }); });

 

2. 隱藏搜索文本框文字

Hide when clicked in the search field, the value.(example can be found below in the comment fields) $(document).ready(function() { $("input.text1").val("Enter your search text here"); textFill($('input.text1')); }); function textFill(input){ //input focus text function
     var originalvalue = input.val(); input.focus( function(){ if( $.trim(input.val()) == originalvalue ){ input.val(''); } }); input.blur( function(){ if( $.trim(input.val()) == '' ){ input.val(originalvalue); } }); }

 

3. 在新窗口中打開連接

XHTML 1.0 Strict doesn’t allow this attribute in the code, so use this to keep the code valid. $(document).ready(function() { //Example 1: Every link will open in a new window
   $('a[href^="http://"]').attr("target", "_blank"); //Example 2: Links with the rel="external" attribute will only open in a new window
   $('a[@rel$='external']').click(function(){ this.target = "_blank"; }); }); // how to use
<a href="http://www.opensourcehunter.com" rel=external>open link</a>

 

4. 檢測瀏覽器

注: 在版本jQuery 1.4中,$.support 替換掉了$.browser 變量 $(document).ready(function() { // Target Firefox 2 and above
if ($.browser.mozilla && $.browser.version >= "1.8" ){ // do something
} // Target Safari
if( $.browser.safari ){ // do something
} // Target Chrome
if( $.browser.chrome){ // do something
} // Target Camino
if( $.browser.camino){ // do something
} // Target Opera
if( $.browser.opera){ // do something
} // Target IE6 and below
if ($.browser.msie && $.browser.version <= 6 ){ // do something
} // Target anything above IE6
if ($.browser.msie && $.browser.version > 6){ // do something
} });

 

5. 預加載圖片

This piece of code will prevent the loading of all images, which can be useful if you have a site with lots of images. $(document).ready(function() { jQuery.preloadImages = function() { for(var i = 0; i<ARGUMENTS.LENGTH; jQuery(?<img { i++)>").attr("src", arguments[i]); } } // how to use $.preloadImages("image1.jpg"); });

 

6. 頁面樣式切換

$(document).ready(function() { $("a.Styleswitcher").click(function() { //swicth the LINK REL attribute with the value in A REL attribute
        $('link[rel=stylesheet]').attr('href' , $(this).attr('rel')); }); // how to use // place this in your header
<LINK rel=stylesheet type=text/css href="default.css">
// the links
<A href="#" rel=default.css>Default Theme</A>
<A href="#" rel=red.css>Red Theme</A>
<A href="#" rel=blue.css>Blue Theme</A>
});

 

7. 列高度相同

若是使用了兩個CSS列,使用此種方式能夠是兩列的高度相同。javascript

$(document).ready(function() { function equalHeight(group) { tallest = 0; group.each(function() { thisHeight = $(this).height(); if(thisHeight > tallest) { tallest = thisHeight; } }); group.height(tallest); } // how to use
$(document).ready(function() { equalHeight($(".left")); equalHeight($(".right")); }); });

 

8. 動態控制頁面字體大小

用戶能夠改變頁面字體大小css

$(document).ready(function() { // Reset the font size(back to default)
  var originalFontSize = $('html').css('font-size'); $(".resetFont").click(function(){ $('html').css('font-size', originalFontSize); }); // Increase the font size(bigger font0
  $(".increaseFont").click(function(){ var currentFontSize = $('html').css('font-size'); var currentFontSizeNum = parseFloat(currentFontSize, 10); var newFontSize = currentFontSizeNum*1.2; $('html').css('font-size', newFontSize); return false; }); // Decrease the font size(smaller font)
  $(".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; }); });

 

9. 返回頁面頂部功能

For a smooth(animated) ride back to the top(or any location). $(document).ready(function() { $('a[href*=#]').click(function() { if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) { var $target = $(this.hash); $target = $target.length && $target || $('[name=' + this.hash.slice(1) +']'); if ($target.length) { var targetOffset = $target.offset().top; $('html,body') .animate({scrollTop: targetOffset}, 900); return false; } } }); // how to use // place this where you want to scroll to
<A name=top></A>
// the link
<A href="#top">go to top</A>
});

 

10. 得到鼠標指針XY值

Want to know where your mouse cursor is? $(document).ready(function() { $().mousemove(function(e){ //display the x and y axis values inside the div with the id XY
    $('#XY').html("X Axis : " + e.pageX + " | Y Axis " + e.pageY); }); // how to use
<DIV id=XY></DIV>
 });

 

11.返回頂部按鈕

你能夠利用 animate 和 scrollTop 來實現返回頂部的動畫,而不須要使用其餘插件。html

// Back to top
$('a.top').click(function () { $(document.body).animate({scrollTop: 0}, 800); return false; }); <!-- Create an anchor tag -->
<a href="#">Back to top</a>

 

改變 scrollTop 的值能夠調整返回距離頂部的距離,而 animate 的第二個參數是執行返回動做須要的時間(單位:毫秒)。java

12.預加載圖片

若是你的頁面中使用了不少不可見的圖片(如:hover 顯示),你可能須要預加載它們:jquery

$.preloadImages = function () { for (var i = 0; i < arguments.length; i++) { $('<img>').attr('src', arguments[i]); } }; $.preloadImages('img/hover1.png', 'img/hover2.png');

 

13.檢查圖片是否加載完成

有時候你須要確保圖片完成加載完成以便執行後面的操做:ajax

$('img').load(function () { console.log('image load successful'); });

 

你能夠把 img 替換爲其餘的 ID 或者 class 來檢查指定圖片是否加載完成。chrome

14.自動修改破損圖像

若是你碰巧在你的網站上發現了破碎的圖像連接,你能夠用一個不易被替換的圖像來代替它們。添加這個簡單的代碼能夠節省不少麻煩:api

$('img').on('error', function () { $(this).prop('src', 'img/broken.png'); });

 

即便你的網站沒有破碎的圖像連接,添加這段代碼也沒有任何害處。瀏覽器

15.鼠標懸停(hover)切換 class 屬性

假如當用戶鼠標懸停在一個可點擊的元素上時,你但願改變其效果,下面這段代碼能夠在其懸停在元素上時添加 class 屬性,當用戶鼠標離開時,則自動取消該 class 屬性:ide

$('.btn').hover(function () { $(this).addClass('hover'); }, function () { $(this).removeClass('hover'); });

 

你只須要添加必要的CSS代碼便可。若是你想要更簡潔的代碼,可使用 toggleClass 方法:

$('.btn').hover(function () { $(this).toggleClass('hover'); });

 

注:直接使用CSS實現該效果多是更好的解決方案,但你仍然有必要知道該方法。

16.禁用 input 字段

有時你可能須要禁用表單的 submit 按鈕或者某個 input 字段,直到用戶執行了某些操做(例如,檢查「已閱讀條款」複選框)。能夠添加 disabled 屬性,直到你想啓用它時:

$('input[type="submit"]').prop('disabled', true);

你要作的就是執行 removeAttr 方法,並把要移除的屬性做爲參數傳入:

$('input[type="submit"]').removeAttr('disabled');

 

17.阻止連接加載

有時你不但願連接到某個頁面或者從新加載它,你可能但願它來作一些其餘事情或者觸發一些其餘腳本,你能夠這麼作:

$('a.no-link').click(function (e) { e.preventDefault(); });

 

18.切換 fade/slide

fade 和 slide 是咱們在 jQuery 中常常使用的動畫效果,它們可使元素顯示效果更好。可是若是你但願元素顯示時使用第一種效果,而消失時使用第二種效果,則能夠這麼作:

// Fade
$('.btn').click(function () { $('.element').fadeToggle('slow'); }); // Toggle
$('.btn').click(function () { $('.element').slideToggle('slow'); });

 

19.簡單的手風琴效果

這是一個實現手風琴效果快速簡單的方法:

// Close all panels
$('#accordion').find('.content').hide(); // Accordion
$('#accordion').find('.accordion-header').click(function () { var next = $(this).next(); next.slideToggle('fast'); $('.content').not(next).slideUp('fast'); return false; });

 

20.讓兩個 DIV 高度相同

有時你須要讓兩個 div 高度相同,而無論它們裏面的內容多少。可使用下面的代碼片斷:

var $columns = $('.column'); var height = 0; $columns.each(function () { if ($(this).height() > height) { height = $(this).height(); } }); $columns.height(height);

 

這段代碼會循環一組元素,並設置它們的高度爲元素中的最大高。

21. 驗證元素是否爲空

This will allow you to check if an element is empty. $(document).ready(function() { if ($('#id').html()) { // do something
 } });

 

22. 替換元素

$(document).ready(function() { $('#id').replaceWith(' <DIV>I have been replaced</DIV> '); });

 

23. jQuery延時加載功能

$(document).ready(function() { window.setTimeout(function() { // do something
   }, 1000); });

 

24. 移除單詞功能

$(document).ready(function() { var el = $('#id'); el.html(el.html().replace(/word/ig, "")); });

 

25. 驗證元素是否存在於jquery對象集合中

$(document).ready(function() { if ($('#id').length) { // do something
 } });

 

26. 使整個DIV可點擊

$(document).ready(function() { $("div").click(function(){ //get the url from href attribute and launch the url
      window.location=$(this).find("a").attr("href"); return false; }); // how to use
<DIV><A href="index.html">home</A></DIV> });

 

27. ID與Class之間轉換

當改變Window大小時,在ID與Class之間切換

$(document).ready(function() { function checkWindowSize() { if ( $(window).width() > 1200 ) { $('body').addClass('large'); } else { $('body').removeClass('large'); } } $(window).resize(checkWindowSize); });

 

28. 克隆對象

$(document).ready(function() { var cloned = $('#id').clone(); // how to use
<DIV id=id></DIV>
 });

 

29. 使元素居屏幕中間位置

$(document).ready(function() { jQuery.fn.center = function () { this.css("position","absolute"); this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px"); this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px"); return this; } $("#id").center(); });

 

30. 寫本身的選擇器

$(document).ready(function() { $.extend($.expr[':'], { moreThen1000px: function(a) { return $(a).width() > 1000; } }); $('.box:moreThen1000px').click(function() { // creating a simple js alert box
      alert('The element that you have clicked is over 1000 pixels wide'); }); });

 

31. 統計元素個數

$(document).ready(function() { $("p").size(); });

 

32. 使用本身的 Bullets

$(document).ready(function() { $("ul").addClass("Replaced"); $("ul > li").prepend("‒ "); // how to use
 ul.Replaced { list-style : none; } });

 

33. 引用Google主機上的Jquery類庫

//Example 1
<SCRIPT src="http://www.google.com/jsapi"></SCRIPT>
<SCRIPT type=text/javascript>
google.load("jquery", "1.2.6"); google.setOnLoadCallback(function() { // do something
}); </SCRIPT><SCRIPT type=text/javascript src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></SCRIPT>

 // Example 2:(the best and fastest way)
<SCRIPT type=text/javascript src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></SCRIPT>

 

34. 禁用Jquery(動畫)效果

$(document).ready(function() { jQuery.fx.off = true; });

 

35. 與其餘Javascript類庫衝突解決方案

$(document).ready(function() { var $jq = jQuery.noConflict(); $jq('#id').show(); });
相關文章
相關標籤/搜索