一 jQuery是什么?
[1] jQuery由美國人John Resig創建,至今已吸引了來自世界各地的眾多 javascript高手加入其team。
[2] jQuery是繼prototype之后又一個優秀的Javascript框架。其宗旨是——WRITE LESS,DO MORE!
[3] 它是輕量級的js庫(壓縮后只有21k) ,這是其它的js庫所不及的,它兼容CSS3,還兼容各種瀏覽器
[4] jQuery是一個快速的,簡潔的javaScript庫,使用戶能更方便地處理HTMLdocuments、events、實現動畫效果,並且方便地為網站提供AJAX交互。
[5] jQuery還有一個比較大的優勢是,它的文檔說明很全,而且各種應用也說得很詳細,同時還有許多成熟的插件可供選擇。
二 什么是jQuery對象?
jQuery 對象就是通過jQuery包裝DOM對象后產生的對象。jQuery 對象是 jQuery 獨有的. 如果一個對象是 jQuery 對象, 那么它就可以使用 jQuery 里的方法: $(“#test”).html();
$("#test").html()
意思是指:獲取ID為test的元素內的html代碼。其中html()是jQuery里的方法
這段代碼等同於用DOM實現代碼: document.getElementById(" test ").innerHTML;
雖然jQuery對象是包裝DOM對象后產生的,但是jQuery無法使用DOM對象的任何方法,同理DOM對象也不能使用jQuery里的方法.亂使用會報錯
約定:如果獲取的是 jQuery 對象, 那么要在變量前面加上$.
var $variable = jQuery 對象
var variable = DOM 對象
$variable[0]:jquery對象轉為dom對象 $("#msg").html(); $("#msg")[0].innerHTML
jquery的基礎語法:$(selector).action()
參考:http://jquery.cuishifeng.cn/
三 尋找元素(選擇器和篩選器)
3.1 選擇器
3.1.1 基本選擇器
$("*") $("#id") $(".class") $("element") $(".class,p,div")
3.1.2 層級選擇器
$(".outer div") $(".outer>div") $(".outer+div") $(".outer~div")
3.1.3 基本篩選器
$("li:first") $("li:eq(2)") $("li:even") $("li:gt(1)")
3.1.4 屬性選擇器
$('[id="div1"]') $('["alex="sb"][id]')
3.1.5 表單選擇器
$("[type='text']")----->$(":text") 注意只適用於input標簽 : $("input:checked")
3.1.6 表單屬性選擇器
:enabled
:disabled
:checked
:selected

<body> <form> <input type="checkbox" value="123" checked> <input type="checkbox" value="456" checked> <select> <option value="1">Flowers</option> <option value="2" selected="selected">Gardens</option> <option value="3" selected="selected">Trees</option> <option value="3" selected="selected">Trees</option> </select> </form> <script src="jquery.min.js"></script> <script> // console.log($("input:checked").length); // 2 // console.log($("option:selected").length); // 只能默認選中一個,所以只能lenth:1 $("input:checked").each(function(){ console.log($(this).val()) }) </script> </body>
3.2 篩選器
3.2.1 過濾篩選器
$("li").eq(2) $("li").first() $("ul li").hasclass("test")
3.2.2 查找篩選器
查找子標簽: $("div").children(".test") $("div").find(".test")
向下查找兄弟標簽: $(".test").next() $(".test").nextAll()
$(".test").nextUntil()
向上查找兄弟標簽: $("div").prev() $("div").prevAll()
$("div").prevUntil()
查找所有兄弟標簽: $("div").siblings()
查找父標簽: $(".test").parent() $(".test").parents()
$(".test").parentUntil()
四 操作元素(屬性,css,文檔處理)
4.1 事件
頁面載入
ready(fn) // 當DOM載入就緒可以查詢及操縱時綁定一個要執行的函數。 $(document).ready(function(){}) -----------> $(function(){})
事件綁定
//語法: 標簽對象.事件(函數) eg: $("p").click(function(){})
事件委派:
$("").on(eve,[selector],[data],fn) // 在選擇元素上綁定一個或多個事件的事件處理函數。
<ul> <li>1</li> <li>2</li> <li>3</li> </ul> <hr> <button id="add_li">Add_li</button> <button id="off">off</button> <script src="jquery.min.js"></script> <script> $("ul li").click(function(){ alert(123) }); $("#add_li").click(function(){ var $ele=$("<li>"); $ele.text(Math.round(Math.random()*10)); $("ul").append($ele) }); // $("ul").on("click","li",function(){ // alert(456) // }) $("#off").click(function(){ $("ul li").off() }) </script>
事件切換
hover事件:
一個模仿懸停事件(鼠標移動到一個對象上面及移出這個對象)的方法。這是一個自定義的方法,它為頻繁使用的任務提供了一種“保持在其中”的狀態。
over:鼠標移到元素上要觸發的函數
out:鼠標移出元素要觸發的函數

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> *{ margin: 0; padding: 0; } .test{ width: 200px; height: 200px; background-color: wheat; } </style> </head> <body> <div class="test"></div> </body> <script src="jquery.min.js"></script> <script> // function enter(){ // console.log("enter") // } // function out(){ // console.log("out") // } // $(".test").hover(enter,out) $(".test").mouseenter(function(){ console.log("enter") }); $(".test").mouseleave(function(){ console.log("leave") }); </script> </html>
4.2 屬性操作
--------------------------CSS類
$("").addClass(class|fn)
$("").removeClass([class|fn])
--------------------------屬性
$("").attr();
$("").removeAttr();
$("").prop();
$("").removeProp();
--------------------------HTML代碼/文本/值
$("").html([val|fn])
$("").text([val|fn])
$("").val([val|fn|arr])
---------------------------
$("#c1").css({"color":"red","fontSize":"35px"})
attr方法使用:

<input id="chk1" type="checkbox" />是否可見 <input id="chk2" type="checkbox" checked="checked" />是否可見 <script> //對於HTML元素本身就帶有的固有屬性,在處理時,使用prop方法。 //對於HTML元素我們自己自定義的DOM屬性,在處理時,使用attr方法。 //像checkbox,radio和select這樣的元素,選中屬性對應“checked”和“selected”,這些也屬於固有屬性,因此 //需要使用prop方法去操作才能獲得正確的結果。 // $("#chk1").attr("checked") // undefined // $("#chk1").prop("checked") // false // ---------手動選中的時候attr()獲得到沒有意義的undefined----------- // $("#chk1").attr("checked") // undefined // $("#chk1").prop("checked") // true console.log($("#chk1").prop("checked"));//false console.log($("#chk2").prop("checked"));//true console.log($("#chk1").attr("checked"));//undefined console.log($("#chk2").attr("checked"));//checked </script>
4.3 each循環
我們知道,
$("p").css("color","red")
是將css操作加到所有的標簽上,內部維持一個循環;但如果對於選中標簽進行不同處理,這時就需要對所有標簽數組進行循環遍歷啦
jquery支持兩種循環方式:
方式一
格式:$.each(obj,fn)
li=[10,20,30,40]; dic={name:"yuan",sex:"male"}; $.each(li,function(i,x){ console.log(i,x) });
方式二
格式:$("").each(fn)
$("tr").each(function(){ console.log($(this).html()) })
其中,$(this)代指當前循環標簽。
each擴展

/* function f(){ for(var i=0;i<4;i++){ if (i==2){ return } console.log(i) } } f(); // 這個例子大家應該不會有問題吧!!! //----------------------------------------------------------------------- li=[11,22,33,44]; $.each(li,function(i,v){ if (v==33){ return ; // ===試一試 return false會怎樣? } console.log(v) }); //------------------------------------------ // 大家再考慮: function里的return只是結束了當前的函數,並不會影響后面函數的執行 //本來這樣沒問題,但因為我們的需求里有很多這樣的情況:我們不管循環到第幾個函數時,一旦return了, //希望后面的函數也不再執行了!基於此,jquery在$.each里又加了一步: for(var i in obj){ ret=func(i,obj[i]) ; if(ret==false){ return ; } } // 這樣就很靈活了: // <1>如果你想return后下面循環函數繼續執行,那么就直接寫return或return true // <2>如果你不想return后下面循環函數繼續執行,那么就直接寫return false // ---------------------------------------------------------------------
4.4 文檔節點處理
//創建一個標簽對象 $("<p>") //內部插入 $("").append(content|fn) ----->$("p").append("<b>Hello</b>"); $("").appendTo(content) ----->$("p").appendTo("div"); $("").prepend(content|fn) ----->$("p").prepend("<b>Hello</b>"); $("").prependTo(content) ----->$("p").prependTo("#foo"); //外部插入 $("").after(content|fn) ----->$("p").after("<b>Hello</b>"); $("").before(content|fn) ----->$("p").before("<b>Hello</b>"); $("").insertAfter(content) ----->$("p").insertAfter("#foo"); $("").insertBefore(content) ----->$("p").insertBefore("#foo"); //替換 $("").replaceWith(content|fn) ----->$("p").replaceWith("<b>Paragraph. </b>"); //刪除 $("").empty() $("").remove([expr]) //復制 $("").clone([Even[,deepEven]])
4.5 動畫效果
顯示隱藏

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="jquery-2.1.4.min.js"></script> <script> $(document).ready(function() { $("#hide").click(function () { $("p").hide(1000); }); $("#show").click(function () { $("p").show(1000); }); //用於切換被選元素的 hide() 與 show() 方法。 $("#toggle").click(function () { $("p").toggle(); }); }) </script> <link type="text/css" rel="stylesheet" href="style.css"> </head> <body> <p>hello</p> <button id="hide">隱藏</button> <button id="show">顯示</button> <button id="toggle">切換</button> </body> </html>
滑動

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="jquery-2.1.4.min.js"></script> <script> $(document).ready(function(){ $("#slideDown").click(function(){ $("#content").slideDown(1000); }); $("#slideUp").click(function(){ $("#content").slideUp(1000); }); $("#slideToggle").click(function(){ $("#content").slideToggle(1000); }) }); </script> <style> #content{ text-align: center; background-color: lightblue; border:solid 1px red; display: none; padding: 50px; } </style> </head> <body> <div id="slideDown">出現</div> <div id="slideUp">隱藏</div> <div id="slideToggle">toggle</div> <div id="content">helloworld</div> </body> </html>
淡入淡出

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="jquery-2.1.4.min.js"></script> <script> $(document).ready(function(){ $("#in").click(function(){ $("#id1").fadeIn(1000); }); $("#out").click(function(){ $("#id1").fadeOut(1000); }); $("#toggle").click(function(){ $("#id1").fadeToggle(1000); }); $("#fadeto").click(function(){ $("#id1").fadeTo(1000,0.4); }); }); </script> </head> <body> <button id="in">fadein</button> <button id="out">fadeout</button> <button id="toggle">fadetoggle</button> <button id="fadeto">fadeto</button> <div id="id1" style="display:none; width: 80px;height: 80px;background-color: blueviolet"></div> </body> </html>
回調函數

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="jquery-2.1.4.min.js"></script> </head> <body> <button>hide</button> <p>helloworld helloworld helloworld</p> <script> $("button").click(function(){ $("p").hide(1000,function(){ alert($(this).html()) }) }) </script> </body> </html>
4.6 css操作
css位置操作
$("").offset([coordinates])
$("").position()
$("").scrollTop([val])
$("").scrollLeft([val])
示例1:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .test1{ width: 200px; height: 200px; background-color: wheat; } </style> </head> <body> <h1>this is offset</h1> <div class="test1"></div> <p></p> <button>change</button> </body> <script src="jquery-3.1.1.js"></script> <script> var $offset=$(".test1").offset(); var lefts=$offset.left; var tops=$offset.top; $("p").text("Top:"+tops+" Left:"+lefts); $("button").click(function(){ $(".test1").offset({left:200,top:400}) }) </script> </html>
示例2:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> *{ margin: 0; } .box1{ width: 200px; height: 200px; background-color: rebeccapurple; } .box2{ width: 200px; height: 200px; background-color: darkcyan; } .parent_box{ position: relative; } </style> </head> <body> <div class="box1"></div> <div class="parent_box"> <div class="box2"></div> </div> <p></p> <script src="jquery-3.1.1.js"></script> <script> var $position=$(".box2").position(); var $left=$position.left; var $top=$position.top; $("p").text("TOP:"+$top+"LEFT"+$left) </script> </body> </html>
示例3:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> body{ margin: 0; } .returnTop{ height: 60px; width: 100px; background-color: peru; position: fixed; right: 0; bottom: 0; color: white; line-height: 60px; text-align: center; } .div1{ background-color: wheat; font-size: 5px; overflow: auto; width: 500px; height: 200px; } .div2{ background-color: darkgrey; height: 2400px; } .hide{ display: none; } </style> </head> <body> <div class="div1 div"> <h1>hello</h1> <h1>hello</h1> <h1>hello</h1> <h1>hello</h1> <h1>hello</h1> <h1>hello</h1> <h1>hello</h1> <h1>hello</h1> <h1>hello</h1> <h1>hello</h1> <h1>hello</h1> <h1>hello</h1> <h1>hello</h1> <h1>hello</h1> <h1>hello</h1> <h1>hello</h1> </div> <div class="div2 div"></div> <div class="returnTop hide">返回頂部</div> <script src="jquery-3.1.1.js"></script> <script> $(window).scroll(function(){ var current=$(window).scrollTop(); console.log(current); if (current>100){ $(".returnTop").removeClass("hide") } else { $(".returnTop").addClass("hide") } }); $(".returnTop").click(function(){ $(window).scrollTop(0) }); </script> </body> </html>
尺寸操作
$("").height([val|fn])
$("").width([val|fn])
$("").innerHeight()
$("").innerWidth()
$("").outerHeight([soptions])
$("").outerWidth([options])
示例:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> *{ margin: 0; } .box1{ width: 200px; height: 200px; background-color: wheat; padding: 50px; border: 50px solid rebeccapurple; margin: 50px; } </style> </head> <body> <div class="box1"> DIVDIDVIDIV </div> <p></p> <script src="jquery-3.1.1.js"></script> <script> var $height=$(".box1").height(); var $innerHeight=$(".box1").innerHeight(); var $outerHeight=$(".box1").outerHeight(); var $margin=$(".box1").outerHeight(true); $("p").text($height+"---"+$innerHeight+"-----"+$outerHeight+"-------"+$margin) </script> </body> </html>
擴展方法 (插件機制)
jQuery.extend(object)
擴展jQuery對象本身。
用來在jQuery命名空間上增加新函數。
在jQuery命名空間上增加兩個函數:
<script> jQuery.extend({ min: function(a, b) { return a < b ? a : b; }, max: function(a, b) { return a > b ? a : b; } }); jQuery.min(2,3); // => 2 jQuery.max(4,5); // => 5 </script>
jQuery.fn.extend(object)
擴展 jQuery 元素集來提供新的方法(通常用來制作插件)
增加兩個插件方法:
<body> <input type="checkbox"> <input type="checkbox"> <input type="checkbox"> <script src="jquery.min.js"></script> <script> jQuery.fn.extend({ check: function() { $(this).attr("checked",true); }, uncheck: function() { $(this).attr("checked",false); } }); $(":checkbox:gt(0)").check() </script> </body>