一、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()
三、尋找元素
3.1、選擇器
1)基本選擇器
$("*") $("#id") $(".class") $("element") $(".class,p,div")
2)層級選擇器
$(".outer div") $(".outer>div") $(".outer+div") $(".outer~div")
3)基本篩選器
$("li:first") $("li:eq(2)") $("li:even") $("li:gt(1)")
4)屬性選擇器
$('[id="div1"]') $('["name="aa"][id]')
5)表單選擇器
$("[type='text']")----->$(":text") //注意只適用於input標簽 : $("input:checked")
示例:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div>hello</div> <a href="">click</a> <p id="p1" alex="sb">pppp</p> <p id="p2" alex="sb">pppp</p> <div class="outer">outer <div class="inner"> inner <p>inner p</p> </div> <p>alex</p> </div> <div class="outer2">Yuan</div> <p>xialv</p> <ul> <li>1111</li> <li>2222</li> <li>3333</li> <li>4444</li> <li>4444</li> <li>4444</li> <li>4444</li> </ul> <input type="text"> <input type="checkbox"> <input type="submit"> <script src="jquery-3.1.1.js"></script> //導入jquery <script> //基本選擇器 // $("div").css("color","red") //div標簽及包含其子標簽 // $("*").css("color","red") //全部 // $("#p1").css("color","red") //id為p1 // $(".outer").css("color","red") //outer class // $(".inner,p,div").css("color","red") //層級選擇器 // $(".outer p").css("color","red") //outer class下的p標簽(后代選擇器) // $(".outer>p").css("color","red") //outer class下一級的p標簽(子代選擇器) // $(".outer+p").css("color","red") //下面毗鄰標簽(緊挨着) // $(".outer~p").css("color","red") //下面標簽,不要求緊挨着 //基本篩選器 // $("li:first").css("color","red") //第一個,也有last // $("li:eq(0)").css("color","red") //$("li:gt(2)").css("color","red") //$("li:lt(2)").css("color","red") //屬性選擇器 // $("[alex='sb'][id='p1']").css("color","red") //表單選擇器 //$("[type='text']").css("width","200px") //$(":text").css("width","400px") </script> </body> </html>
3.2、篩選器
1)過濾篩選器
$("li").eq(2) $("li").first() $("ul li").hasclass("test")
2)查找篩選器
$("div").children(".test") //子代選擇器 $("div").find(".test") //后代 //向下查找 $(".test").next() $(".test").nextAll() $(".test").nextUntil() //向上查找 $("div").prev() $("div").prevAll() $("div").prevUntil() //父輩 $(".test").parent() $(".test").parents() $(".test").parentUntil() $("div").siblings()
示例:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <a href="">click</a> <p id="p1" alex="sb">pppp</p> <p id="p2" alex="sb">pppp</p> <div class="outer">outer <div class="inner"> inner <p>inner p</p> </div> <p>alex</p> </div> <div class="outer2">Yuan</div> <p>xialv</p> <ul> <li class="begin">1111</li> <li>2222</li> <li>3333</li> <li>4444</li> <li>4444</li> <li id="end">4444</li> <li>4444</li> </ul> <input type="text"> <input type="checkbox"> <input type="submit"> <script src="jquery-3.1.1.js"></script> <script> //篩選器 //$("li").eq(2).css("color","red"); //$("li").first().css("color","red"); //$("li").last().css("color","red"); //查找篩選器 //$(".outer").children("p").css("color","red"); //$(".outer").find("p").css("color","red"); //$("li").eq(2).next().css("color","red"); //$("li").eq(2).nextAll().css("color","red"); //$("li").eq(2).nextUntil("#end").css("color","red"); //$("li").eq(4).prev().css("color","red"); //$("li").eq(4).prevAll().css("color","red"); //$("li").eq(4).prevUntil("li:eq(0)").css("color","red"); //console.log($(".outer .inner p").parent().html()) //$(".outer .inner p").parents().css("color","red"); //$(".outer .inner p").parentsUntil("body").css("color","red"); $(".outer").siblings().css("color","red") </script> </body> </html>
實例:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .outer{ height: 1000px; width: 100%; } .menu{ float: left; background-color: beige; width: 30%; height: 500px; } .content{ float: left; background-color: rebeccapurple; width: 70%; height: 500px; } .title{ background-color: aquamarine; line-height: 40px; } .hide{ display: none; } </style> </head> <body> <div class="outer"> <div class="menu"> <div class="item"> <div class="title" onclick="show(this)">菜單一</div> <div class="con"> <div>111</div> <div>111</div> <div>111</div> </div> </div> <div class="item"> <div class="title" onclick="show(this)">菜單二</div> <div class="con hide"> <div>222</div> <div>222</div> <div>222</div> </div> </div> <div class="item"> <div class="title" onclick="show(this)">菜單三</div> <div class="con hide"> <div>333</div> <div>333</div> <div>333</div> </div> </div> </div> <div class="content"></div> </div> <script src="jquery-3.1.1.js"></script> <script> function show(self) { $(self).next().removeClass("hide"); //自身菜單內容顯示 $(self).parent().siblings().children(".con").addClass("hide"); //其他菜單內容隱藏 } </script> </body> </html>
四、元素操作
4.1、屬性操作
//屬性 $("").attr(); $("").removeAttr(); $("").prop(); $("").removeProp(); //CSS類 $("").addClass(class|fn) $("").removeClass([class|fn]) //HTML代碼/文本/值 $("").html([val|fn]) $("").text([val|fn]) $("").val([val|fn|arr]) $("").css("color","red")
注意:attr與prop區別
<input id="chk1" type="checkbox" />是否可見 <input id="chk2" type="checkbox" checked="checked" />是否可見 <script> //對於HTML元素本身就帶有的固有屬性,在處理時,使用prop方法。 //對於HTML元素我們自己自定義的DOM屬性,在處理時,使用attr方法。 //像checkbox,radio和select這樣的元素,選中屬性對應“checked”和“selected”,這些也屬於固有屬性,因此 //需要使用prop方法去操作才能獲得正確的結果。 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>
示例:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div class="div1" con="c1"></div> <input type="checkbox" checked="checked">是否可見 <input type="checkbox">是否可見 <input type="text" value="123"> <div value="456"></div> <div id="id1"> uuuuu <p>ppppp</p> </div> <script src="jquery-3.1.1.js"></script> <script> // console.log($("div").hasClass("div1")); //true // console.log($("div").attr("con")) //c1 // console.log($("div").attr("con","c2")) //設置屬性 // console.log($(":checkbox:first").attr("checked")) //checked // console.log($(":checkbox:last").attr("checked")) //undefined // console.log($(":checkbox:first").prop("checked")) //true // console.log($(":checkbox:last").prop("checked")) //false // console.log($("div").prop("con")) //undefined // console.log($("div").prop("class")) //div1 // console.log($("#id1").html()); //uuuuu <p>ppppp</p> // console.log($("#id1").text()); //uuuuu ppppp // console.log($("#id1").html("<h1>YUAN</h1>")) // console.log($("#id1").text("<h1>YUAN</h1>")) // console.log($("#id1").html()); // console.log($("#id1").text()); //<h1>YUAN</h1> //固有屬性 // console.log($(":text").val()); //123 // console.log($(":text").next().val()) //沒有值 // $(":text").val("789"); // $("div").css({"color":"red","background-color":"green"}) </script> </body> </html>
jquery循環遍歷:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <p>1111</p> <p>2222</p> <p>3333</p> <script src="jquery-3.1.1.js"></script> <script> arr=[11,22,33]; //使用遍歷 // for (var i=0;i<arr.length;i++){ // $("p").eq(i).html(arr[i]) // } // 使用jquery遍歷方式一 // $.each(arr,function (x,y) { //x下標,y值 // console.log(x); // console.log(y); // }); //使用jquery遍歷方式二(常用) $("p").each(function () { //對所有p標簽遍歷 console.log($(this)); $(this).html("hello") }) </script> </body> </html>
示例-全反選:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <button onclick="selectall();">全選</button> <button onclick="cancel();">取消</button> <button onclick="reverse();">反選</button> <hr> <table border="1"> <tr> <td><input type="checkbox"></td> <td>111</td> </tr> <tr> <td><input type="checkbox"></td> <td>222</td> </tr> <tr> <td><input type="checkbox"></td> <td>333</td> </tr> <tr> <td><input type="checkbox"></td> <td>444</td> </tr> </table> <script src="jquery-3.1.1.js"></script> <script> function selectall() { $(":checkbox").each(function () { $(this).prop("checked",true) }) } function cancel() { $(":checkbox").each(function () { $(this).prop("checked",false) }) } function reverse() { $(":checkbox").each(function () { //方式一 $(this).prop("checked",!$(this).prop("checked")); //方式二 // if($(this).prop("checked")){ // $(this).prop("checked",false) // } // // else { // $(this).prop("checked",true) // } }) } </script> </body> </html>
示例-模態對話框:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .back{ background-color: rebeccapurple; height: 2000px; } .shade{ position: fixed; top: 0; bottom: 0; left:0; right: 0; background-color: coral; opacity: 0.4; } .hide{ display: none; } .models{ position: fixed; top: 50%; left: 50%; margin-left: -100px; margin-top: -100px; height: 200px; width: 200px; background-color: gold; } </style> </head> <body> <div class="back"> <input id="ID1" type="button" value="click" onclick="action1(this)"> </div> <div class="shade hide"></div> <div class="models hide"> <input id="ID2" type="button" value="cancel" onclick="action2(this)"> </div> <script src="jquery-3.1.1.js"></script> <script> function action1(self){ $(self).parent().siblings().removeClass("hide"); } function action2(self) { //方式一 // $(self).parent().addClass("hide") // $(self).parent().prev().addClass("hide") //方式二 // $(self).parent().addClass("hide").prev().addClass("hide"); //方式三 $(self).parent().parent().children(".models,.shade").addClass("hide") } </script> </body> </html>
4.2、文檔處理
//創建一個標簽對象 $("<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]])
實例:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div class="c1"> <p>PPP</p> </div> <button>add</button> <script src="jquery-3.1.1.js"></script> <script> $("button").click(function () { // $(".c1").append("<h1>HELLO YUAN</h1>") var $ele=$("<h1></h1>"); //創建標簽 $ele.html("HELLO WORLD!"); //修改標簽內容 $ele.css("color","red"); //修改標簽內容顏色顯示 //內部插入 // $(".c1").append($ele); //$ele.appendTo(".c1") //$(".c1").prepend($ele); //$ele.prependTo(".c1") //外部插入 //$(".c1").after($ele) //$ele.insertAfter(".c1") //$(".c1").before($ele) //$ele.insertBefore(".c1") //替換 //$("p").replaceWith($ele) //刪除與清空 // $(".c1").empty() //清除本標簽的內容,但標簽自身還在 // $(".c1").remove() //標簽整個清除 //clone // var $ele2= $(".c1").clone(); // $(".c1").after($ele2) //存在問題:會成倍增加 }) </script> </body> </html>
clone成倍增加問題解決:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div class="outer"> <div class="item"> <button onclick="add(this)">+</button> <input type="text"> </div> </div> <script src="jquery-3.1.1.js"></script> <script> function add(self) { //var $clone_obj=$(".item").clone(); var $clone_obj=$(self).parent().clone(); $clone_obj.children("button").html("-").attr("onclick","remove_obj(this)"); $(".outer").append($clone_obj) } function remove_obj(self) { $(self).parent().remove() } </script> </body> </html>
4.3、css操作
//CSS $("").css(name|pro|[,val|fn]) //位置 $("").offset([coordinates]) $("").position() $("").scrollTop([val]) $("").scrollLeft([val]) //尺寸 $("").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: 0px; padding: 0px; } .div1,.div2{ width: 200px; height: 100px; } .div1{ border: 5px solid rebeccapurple; padding: 20px; margin: 2px; background-color: antiquewhite; } .div2{ background-color: rebeccapurple; } /*.outer{*/ /*position: relative;*/ /*}*/ </style> </head> <body> <div class="div1"></div> <div class="outer"> <div class="div2"></div> </div> <script src="jquery-3.1.1.js"></script> <script> // offset()相對於視口的偏移量 // console.log($(".div1").offset().top); // console.log($(".div1").offset().left); // // console.log($(".div2").offset().top); // console.log($(".div2").offset().left); //position():相對於已經定位的父標簽的偏移量 // console.log($(".div1").position().top); // console.log($(".div1").position().left); // console.log($(".div2").position().top); // console.log($(".div2").position().left); // console.log($(".div1").height("300px")); // console.log($(".div1").innerHeight()); // console.log($(".div1").outerHeight()); // console.log($(".div1").outerHeight(true)); </script> </body> </html>
實例-返回頂部:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> *{ margin: 0px; padding: 0px; } .div2{ width: 100%; height: 800px; } .div1{ width: 40%; height: 150px; background-color: antiquewhite; overflow: auto; } .div2{ background-color: rebeccapurple; } .returnTop{ position: fixed; right: 20px; bottom: 20px; width: 90px; height: 50px; background-color: gray; color: white; text-align: center; line-height: 50px; } .hide{ display: none; } </style> </head> <body> <div class="div1"> <h1>1111</h1> <h1>1111</h1> <h1>1111</h1> <h1>1111</h1> <h1>1111</h1> <h1>1111</h1> </div> <div class="div2"> <button onclick="returnTop()">return</button> </div> <div class="returnTop hide" onclick="returnTop()">返回頂部</div> <script src="jquery-3.1.1.js"></script> <script> window.onscroll=function () { //監控窗口滾輪狀態 // console.log($(window).scrollTop()); if($(window).scrollTop()>300){ $(".returnTop").removeClass("hide") }else { $(".returnTop").addClass("hide") } }; function returnTop() { $(window).scrollTop(0) } $(".div2 button").click(function () { $(".div1").scrollTop(0) }) </script> </body> </html>
五、事件
//頁面載入 ready(fn) //當DOM載入就緒可以查詢及操縱時綁定一個要執行的函數。 $(document).ready(function(){}) -----------> $(function(){}) //事件處理 $("").on(eve,[selector],[data],fn) // 在選擇元素上綁定一個或多個事件的事件處理函數。 // .on的selector參數是篩選出調用.on方法的dom元素的指定子元素,如: // $('ul').on('click', 'li', function(){console.log('click');})就是篩選出ul下的li給其綁定 // click事件; //[selector]參數的好處: 好處在於.on方法為動態添加的元素也能綁上指定事件;如: //$('ul li').on('click', function(){console.log('click');})的綁定方式和 //$('ul li').bind('click', function(){console.log('click');})一樣;我通過js給ul添加了一個 //li:$('ul').append('<li>js new li<li>');這個新加的li是不會被綁上click事件的 //但是用$('ul').on('click', 'li', function(){console.log('click');}方式綁定,然后動態添加 //li:$('ul').append('<li>js new li<li>');這個新生成的li被綁上了click事件 [data]參數的調用: function myHandler(event) { alert(event.data.foo); } $("li").on("click", {foo: "bar"}, myHandler)
示例:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <ul> <li>1111</li> <li>2222</li> <li>3333</li> <li>4444</li> </ul> <button>add</button> <script src="jquery-3.1.1.js"></script> <script> // 事件准備加載方式一 // $(document).ready(function () { // $("ul li").html(5); // }); // 事件准備加載方式二 // $(function () { // $("ul li").html(5); // }); //事件綁定簡單形式 var eles=document.getElementsByTagName("li") eles.onclick=function () { alert(123) } $("ul li").click(function () { //綁定事件一 alert(6666) }); // $("ul li").bind("click",function () { //綁定事件二 // alert(777) // }); // $("ul li").unbind("click") //事件綁定解除 // 事件委托 $('ul').on("click","li",function () { alert(999); }); $("button").click(function () { var $ele=$("<li>"); var len=$("ul li").length; $ele.html((len+1)*1111); $("ul").append($ele) }); </script> </body> </html>
實例-面板拖動:
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> </head> <body> <div style="border: 1px solid #ddd;width: 600px;position: absolute;"> <div id="title" style="background-color: black;height: 40px;color: white;"> 標題 </div> <div style="height: 300px;"> 內容 </div> </div> <script type="text/javascript" src="jquery-3.1.1.js"></script> <script> $(function(){ // 頁面加載完成之后自動執行 $('#title').mouseover(function(){ $(this).css('cursor','move'); }).mousedown(function(e){ //console.log($(this).offset()); var _event = e || window.event; // 原始鼠標橫縱坐標位置 var ord_x = _event.clientX; var ord_y = _event.clientY; var parent_left = $(this).parent().offset().left; var parent_top = $(this).parent().offset().top; $(this).bind('mousemove', function(e){ var _new_event = e || window.event; var new_x = _new_event.clientX; var new_y = _new_event.clientY; var x = parent_left + (new_x - ord_x); var y = parent_top + (new_y - ord_y); $(this).parent().css('left',x+'px'); $(this).parent().css('top',y+'px'); }) }).mouseup(function(){ $(this).unbind('mousemove'); }); }) </script> </body> </html>
六、動畫效果
6.1、顯示隱藏
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="jquery-3.1.1.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>
6.2、滑動
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="jquery-3.1.1.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>
6.3、淡入淡出
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="jquery-3.1.1.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>
6.4、回調函數
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="jquery-3.1.1.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>
七、拓展方法(插件機制)
7.1、定義拓展方法
<script> $.extend(object) //為JQuery 添加一個靜態方法。 $.fn.extend(object) //為JQuery實例添加一個方法。 jQuery.extend({ min: function(a, b) { return a < b ? a : b; }, max: function(a, b) { return a > b ? a : b; } }); console.log($.min(3,4)); //----------------------------------------------------------------------- $.fn.extend({ "print":function(){ for (var i=0;i<this.length;i++){ console.log($(this)[i].innerHTML) } } }); $("p").print(); </script> //----------------------------------------------------------------------- $.fn.extend({ GetText:function () { for(var i=0;i<this.length;i++){ console.log(this[i].innerHTML) } $.each($(this),function (x,y) { //console.log(y.innerHTML) //console.log($(y).html()) }) } }); $("p").GetText()