第四篇 前端学习之JQuery基础
一 jQuery是什么???
jQuery就是一個JavaScript的庫。
<1> jQuery由美國人John Resig創(chuàng)建,至今已吸引了來自世界各地的眾多 javascript高手加入其team。
<2>jQuery是繼prototype之后又一個優(yōu)秀的Javascript框架。其宗旨是——WRITE LESS,DO MORE!
<3>它是輕量級的js庫(壓縮后只有21k) ,這是其它的js庫所不及的,它兼容CSS3,還兼容各種瀏覽器(IE6.0+, FF 1.5+, Safari 2.0+, Opera 9.0+);
<4>jQuery是一個快速的,簡潔的javaScript庫,使用戶能更方便地處理HTMLdocuments、events、實現(xiàn)動畫效果,并且方便地為網(wǎng)站提供AJAX交互。
AJAX:實現(xiàn)前端向后端發(fā)送數(shù)據(jù)——非常重要
<5>jQuery還有一個比較大的優(yōu)勢是,它的文檔說明很全,而且各種應(yīng)用也說得很詳細,同時還有許多成熟的插件可供選擇。
參考JQuery文檔:http://jquery.cuishifeng.cn/
二 什么是jQuery對象?
?jQuery?對象就是通過jQuery包裝DOM對象后產(chǎn)生的對象。
?jQuery?對象是?jQuery?獨有的.?
?如果一個對象是?jQuery?對象,?那么它就可以使用?jQuery?里的方法: $(“#test”).html();
$("#test").html() //意思是指:獲取ID為test的元素內(nèi)的html代碼。其中html()是jQuery里的方法 // 這段代碼等同于用DOM實現(xiàn)代碼: document.getElementById(" test ").innerHTML; //雖然jQuery對象是包裝DOM對象后產(chǎn)生的,但是jQuery無法使用DOM對象的任何方法,同理DOM對象也不能使用jQuery里的方法.亂使用會報錯//約定:如果獲取的是 jQuery 對象, 那么要在變量前面加上$. var $variable = jQuery 對象 定義jquery對象時,變量前就加個 $符號,明確告訴人家這是jQuery對象 var variable = DOM 對象$variable[0]:jquery對象轉(zhuǎn)為dom對象 $("#msg").html(); $("#msg")[0].innerHTMLjquery的基礎(chǔ)語法:$(selector).action()
幸福生活的開始從導(dǎo)入jQuery庫開始
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>Title</title> </head> <body><div>hello</div><!--要使用JQuery,必選先通過script引入jQueryku才行--><script src="jquery-3.3.1.js"></script><script>// $符號:就代表JQuery對象,里面有無窮盡的語法,全在$里// 找到div標(biāo)簽: $("div")// 對div標(biāo)簽進行樣式設(shè)置:$("div").css("color","red"); $("div").css("color","red");// 當(dāng)然也可以用jQuery,但是用$符號更簡單jQuery("div").css("color","red");</script> </body> </html>?
三 尋找元素(選擇器和篩選器)?
3.1 ? 選擇器
3.1.1 基本選擇器? ? ??
$("*"): 對所有標(biāo)簽進行操作$("#id"):通過id找標(biāo)簽
$(".class") :通過class屬性找
$("element") :通過標(biāo)簽名字找
$(".class,p,div"):可以一次找多個元素 <!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>Title</title> </head> <body><div>hello</div><p id="p1">ppp</p><a href="">click</a><div class="outer">outers<div class="inner">inner</div></div><div class="outer">helllllllo</div><!--要使用JQuery,必選先通過script引入jQueryku才行--><script src="jquery-3.3.1.js"></script><script>// $("*").css("color","red");// $("#p1").css("color","blue");// $(".inner").css("color","green");// $(".outer").css("color","brown"); // jQuery自己做了遍歷// $(".inner,p,div").css("color","red");$("p").css("color","red"); // 通過element找,即通過標(biāo)簽的名字去找</script> </body> </html> 示例
3.1.2 層級選擇器:處理層級嵌套, 后代(兒子)選擇器? ? ??
$(".outer div") :后代選擇器$(".outer>div") :子代選擇器
$(".outer+div") :向下找緊挨著的兄弟標(biāo)簽
$(".outer~div") :向下找兄弟標(biāo)簽,可以不緊挨著outer的,也能找到 <!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>Title</title> </head> <body><div>hello</div><p id="p1">ppp</p><a href="">click</a><div class="outer">outers<div class="inner">inner<p>innerP</p></div><p>alex</p></div><div>lalal</div><p>隔著一個,向下也能找到兄弟標(biāo)簽</p><p>向下緊挨著的兄弟標(biāo)簽</p><!--<div class="outer">helllllllo</div>--><!--要使用JQuery,必選先通過script引入jQueryku才行--><script src="jquery-3.3.1.js"></script><script>// 后代選擇器:// 找到class屬性值為outer的下面的所有 p 標(biāo)簽,不管是子代,孫子代,還是重孫子代都找到$(".outer p").css("color","red");// 子代選擇器:// 找到找到class屬性值為outer的下面的所有 p 標(biāo)簽且找到的p標(biāo)簽都是outer的兒子代$(".outer > p").css("color","red");// 向下緊挨著的兄弟標(biāo)簽// $(".outer + p").css("color","blue");// 向下找兄弟標(biāo)簽(同級的),可以不緊挨著$(".outer ~ p").css("color","green");</script> </body> </html> 層級選擇器示例
3.1.3 基本篩選器? ? ??
選擇出后再過濾一遍的意思
$("li:first") $("li:eq(2)") $("li:even") $("li:gt(1)") <!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>Title</title> </head> <body><ul><li>111</li><li>222</li><li>333</li><li>444</li><li>555</li><li>666</li><li>777</li><li>888</li> </ul><script src="jquery-3.3.1.js"></script> <script>console.log($("li"));// 對第一個li標(biāo)簽操作$("li:first").css("color","red");// 對最后一個li標(biāo)簽操作$("li:last").css("color","red"); // 對其他第n個操作$("li:eq(1)").css("color","blue");// 控制偶數(shù)行,從0開始的$("li:even").css("color","green");//控制奇數(shù)行$("li:odd").css("color","brown");//篩選出的是大于索引為3的標(biāo)簽,不包含索引3$("li:gt(3)").css("color","brown");//篩選出的是小于索引為3的標(biāo)簽,不包含索引3$("li:lt(3)").css("color","red");</script> </body> </html> 基本篩選器3.1.4?屬性選擇器? ??
通過標(biāo)簽的屬性來查找屬性。自己也可以添加屬性
$('[id="div1"]') $('[alex="sb"][id]')? <!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>Title</title> </head> <body><div>hello</div><p id="p1" alex="bbb">ppp屬性選擇器</p><p id="p2" alex="bbb">ppp屬性選擇器</p><p id="p3" alex="bbb">ppp屬性選擇器</p><a href="">click</a><!--<div class="outer">helllllllo</div>--><!--要使用JQuery,必選先通過script引入jQueryku才行--><script src="jquery-3.3.1.js"></script><script>// 通過屬性選擇器查找$("[alex='bbb']").css("color","red");// 如果有多個屬性標(biāo)簽屬性名相同,可以多層選擇$("[alex='bbb'][id='p2']").css("color","blue");</script> </body> </html> 屬性選擇器3.1.5 表單選擇器? ? ?
$("[type='text']")----->$(":text") 注意 :只適用于input標(biāo)簽$("input:checked") <!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>Title</title> </head> <body><input type="text"> <input type="checkbox"> <input type="submit"><script src="jquery-3.3.1.js"></script> <script>// $("[type='text']").css("width","200px");//只有input表單選擇器才可以通過冒號的形式篩選$(":text").css("width","400px");</script> </body> </html> 表單選擇器
?
實例之左側(cè)菜單
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>left_menu</title><style>.menu{height: 500px;width: 30%;background-color: gainsboro;float: left;}.content{height: 500px;width: 70%;background-color: rebeccapurple;float: left;}.title{line-height: 50px;background-color: #425a66;color: forestgreen;}.hide{display: none;}</style> </head> <body><div class="outer"><div class="menu"><div class="item"><div class="title">菜單一</div><div class="con"><div>111</div><div>111</div><div>111</div></div></div><div class="item"><div class="title">菜單二</div><div class="con hide"><div>111</div><div>111</div><div>111</div></div></div><div class="item"><div class="title">菜單三</div><div class="con hide"><div>111</div><div>111</div><div>111</div></div></div></div><div class="content"></div></div> <script src="jquery-3.2.1.js"></script> <script>$(".item .title").click(function () {$(this).next().removeClass("hide").parent().siblings().children(".con").addClass("hide");// $(this).next().removeClass("hide"); // $(this).parent().siblings().children(".con").addClass("hide"); }) </script></body> </html> View Code實例之tab切換
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>tab</title><script>function tab(self){var index=$(self).attr("xxx");$("#"+index).removeClass("hide").siblings().addClass("hide");$(self).addClass("current").siblings().removeClass("current");}</script><style>*{margin: 0px;padding: 0px;}.tab_outer{margin: 0px auto;width: 60%;}.menu{background-color: #cccccc;/*border: 1px solid red;*/line-height: 40px;}.menu li{display: inline-block;}.menu a{border-right: 1px solid red;padding: 11px;}.content{background-color: tan;border: 1px solid green;height: 300px;}.hide{display: none;}.current{background-color: darkgray;color: yellow;border-top: solid 2px rebeccapurple;}</style> </head> <body><div class="tab_outer"><ul class="menu"><li xxx="c1" class="current" οnclick="tab(this);">菜單一</li><li xxx="c2" οnclick="tab(this);">菜單二</li><li xxx="c3" οnclick="tab(this);">菜單三</li></ul><div class="content"><div id="c1">內(nèi)容一</div><div id="c2" class="hide">內(nèi)容二</div><div id="c3" class="hide">內(nèi)容三</div></div></div> </body> </html> View Code3.2 篩選器
?3.2.1??過濾篩選器? ??
與3.1.3基本篩選器實現(xiàn)的功能一樣,但是推薦以后都用過濾篩選器這種方式實現(xiàn)。應(yīng)該篩選條件是寫在外面的,更靈活
$("li").eq(2)$("li").first()
$("ul li").hasclass("test") <!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>Title</title> </head> <body><ul><li>111</li><li>222</li><li>333</li><li>444</li><li>555</li><li>666</li><li>777</li><li>888</li> </ul><input type="text"> <input type="checkbox"> <input type="submit"><script src="jquery-3.3.1.js"></script> <script>$("li").eq(2).css("color","red");$("li").first().css("color","red");$("li").last().css("color","red");</script> </body> </html> 過濾篩選器示例 <!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>Title</title> </head> <body><li class="title">ll</li><script src="jquery-3.3.1.js"></script><script>// 查詢某標(biāo)簽是否具有某屬性console.log($("li").hasClass("title2"));</script> </body> </html> 查詢某標(biāo)簽是否具有某屬性
3.2.2??查找篩選器(基本四組)
非常重要,沒有項目不用到這種篩選方法。
1. 找子代$("div").children(".test")
$("div").find(".test")
2.找下一個 $(".test").next()
$(".test").nextAll()
$(".test").nextUntil()
3. 找上一個,完全與next組對應(yīng)的 $("div").prev()
$("div").prevAll()
$("div").prevUntil()
4. $(".test").parent()
$(".test").parents()
$(".test").parentUntil()
$("div").siblings() <!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>Title</title> </head> <body><p id="p1" alex="sb">pppp</p> <p id="p2" alex2="sb">pppp2</p><div class="outer"> outer<div class="inner">inner<p>孫子p標(biāo)簽</p></div><p>兒子p標(biāo)簽</p> </div> <div class="outer2">Yuan</div> <p>先走一步</p><ul><li>111</li><li class="begin">222</li><li>333</li><li>444</li><li>555</li><li>666</li><li id="end">777</li><li>888</li> </ul><input type="text"> <input type="checkbox"> <input type="submit"><script src="jquery-3.3.1.js"></script> <script>// 1. 根據(jù)一個已知的標(biāo)簽找到它的子代標(biāo)簽// 只找子標(biāo)簽$(".outer").children("p").css("color","red");// 找到.outer下的所有p標(biāo)簽$(".outer").find("p").css("color","red");// 2.next組查找 // 找到索引為2的li標(biāo)簽的下一個標(biāo)簽$("li").eq(2).next().css("color","red"); // 找到索引為2的li標(biāo)簽后面的所有標(biāo)簽$("li").eq(2).nextAll().css("color","red"); // 從索引為2的li標(biāo)簽開始,一直找到 id=end的li標(biāo)簽,左開右開區(qū)間)$("li").eq(2).nextUntil("#end").css("color","red");// 3.prev組查找:向上找 // 找到索引為2的li標(biāo)簽的上一個標(biāo)簽$("li").eq(2).prev().css("color","red");// 找到索引為2的li標(biāo)簽上面的所有標(biāo)簽$("li").eq(2).prevAll().css("color","red");// 從索引為5的li標(biāo)簽開始,一直找到 id=end的li標(biāo)簽,左開右開區(qū)間)$("li").eq(5).prevUntil(".begin").css("color","red");// 4. parent 組查找$(".outer .inner p").parent().css("color","red");$(".outer .inner p").parents().css("color","red");// 常用$(".outer .inner p").parentsUntil("body").css("color","red");// siblings 用的最多的. 找兄弟標(biāo)簽,上下的全部兄弟標(biāo)簽都找出來,除了.outer$(".outer").siblings().css("color", "red");</script> </body> </html> 示例 示例
?
四 操作元素(屬性,css,文檔處理)
4.1 屬性操作
--------------------------屬性: attr 和 prop的使用方法和作用是完全一樣的。區(qū)別只在于,attr既能處理固有屬性,又能處理自定義屬性,而prop只能處理固有屬性 $("").attr(); -->常用的屬性標(biāo)簽:既可以取到屬性值,也可以給屬性設(shè)置值;既可以處理固有屬性,也可以處理自定義屬性,推薦attr只用來處理自定義屬性 $("").removeAttr(); $("").prop();-->獲取屬性,如果存在返回true,如果不存在返回false,用于判斷使用;只能處理固有的屬性,所以推薦對所有固有屬性,都用prop處理 $("").removeProp(); --------------------------CSS類 $("").addClass(class|fn) --> 見左側(cè)菜單實例 $("").removeClass([class|fn])-->見左側(cè)菜單實例--------------------------HTML代碼/文本/值
要處理的標(biāo)簽內(nèi)部如果是html,就得用html()處理;
要處理的標(biāo)簽內(nèi)部如果是text,就得用text()處理; $("").html([val|fn]) --> 用html,可以區(qū)別出里面是文本還是標(biāo)簽,然后進行替換 $("").text([val|fn]) --> text,()里的內(nèi)容全部當(dāng)做純文本來處理,去替換 $("").val([val|fn|arr])--> val不能隨便用,只能處理固有屬性:input,option,select,表單類都有value屬; 可以獲取值也可以替換原來的值 --------------------------- $("").css("color","red")
?需求:
?常見的web項目左側(cè)有個菜單,點擊某個菜單,該菜單下面的子菜單顯示,其他菜單隱藏
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>Title</title><!--2. 再處理布局--><style>.outer{height: 1000px;width: 100%;background-color: gray;}.menu{float: left;background-color: rebeccapurple;width: 30%;height: 500px;}.title{background-color: lightgreen;}.hide{display: none;}</style> </head> <body><!--步驟:1. 先寫html--><div class="outer"><div class="menu"><div class="item"><div class="title" οnclick="show(this)">菜單一</div><!--默認(rèn)進來菜單一不是折疊的,可以去掉hide屬性,如果是折疊的,就像下面那樣寫上hide--><div class="con hide"><div>111</div><div>111</div><div>111</div></div></div><div class="item"><div class="title" οnclick="show(this)">菜單二</div><div class="con hide"><div>222</div><div>222</div><div>222</div></div></div><div class="item"><div class="title" οnclick="show(this)">菜單三</div><div class="con hide"><div>333</div><div>333</div><div>333</div></div></div></div><div class="content"></div></div><!--3.JQuery實現(xiàn)功能-->// 先引入Jquery<script src="jquery-3.3.1.js"></script><script>// this表示找到當(dāng)前點擊的元素,function函數(shù)里用self接function show(self) {// 1)實現(xiàn)點哪個菜單,該菜單下面的子菜單展示出來;// 用到JQuery的屬性操作知識了,找到當(dāng)前點擊的菜單,移除它的hide屬性$(self).next().removeClass("hide");// 2)同時其他菜單的子菜單全部折疊// 先找到當(dāng)前點擊菜單的父元素,再通過siblings找到父元素的所有兄弟元素,然后找到所有兄弟元素下面的子元素// 里的 con屬性,為其增加 hide屬性// 如果沒有hide屬性,就增加,如果已經(jīng)有hide屬性就不增加$(self).parent().siblings().children(".con").addClass("hide");}</script> </body> </html> 左側(cè)菜單顯示折疊實例:addClass, removeClass <!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"> 是否可見1<input type="checkbox" > 是否可見2<script src="jquery-3.3.1.js"></script><script>// 1. attr()屬性// attr屬性,取出con屬性的值console.log($("div").attr("con"));// attr屬性,給con屬性設(shè)置值;本來沒有con1屬性,還可以新增這個屬性并設(shè)置屬性值console.log($("div").attr("con","c2"));console.log($("div").attr("con1","c3"));// 2.取input標(biāo)簽的屬性,看prop和attr的區(qū)別console.log($(":checkbox:first").attr("checked"));console.log($(":checkbox:last").attr("checked"));// prop返回的是屬性的值,存在是true,不存在是false,方便用于判斷// prop主要用來處理固有屬性,比如上面自定義的con屬性找不到的;// 如果是自己定義的屬性,都用attr,更好的區(qū)分固有屬性和自定義屬性console.log($(":checkbox:first").prop("checked")); // attr和prop括號內(nèi)都是些的屬性名稱,而不是具體的屬性值console.log($(":checkbox:last").prop("checked"));// 自定義屬性,找不到的console.log($(":checkbox:last").prop("con"));</script> </body> </html> attr和prop的區(qū)別 <!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/html"> <head><meta charset="UTF-8"><title>Title</title> </head> <body><div class="div1" con="c1"></div><input type="checkbox" checked="checked"> 是否可見1<input type="checkbox" > 是否可見2 </br><input type="text" value="請輸入你的大名"><div value = "234">測試value是否可以檢測到</div><div id="id1">uuuuu<p>ppppp</p></div><script src="jquery-3.3.1.js"></script><script>// html()把標(biāo)簽里面的所有內(nèi)容都取出來了,有其他標(biāo)簽也會取出來console.log($("#id1").html());// text()只會把下面的文本內(nèi)容取出來,帶標(biāo)簽的文本,也只會把文本取出來console.log($("#id1").text());// html()里面如果加了內(nèi)容,會把下面原理所有的內(nèi)容都會用新內(nèi)容替換,相當(dāng)于重新設(shè)值了console.log($("#id1").html("<h1>Ma Ge</h1>>"));console.log($("#id1").html("用文本替換"));// 如果是text(),就會把text里面的所有內(nèi)容都當(dāng)做純文本來處理的// console.log($("#id1").text("<h1>Ma Ge</h1>>"));// val不能隨便用,只能處理固有屬性:input,option,select,表單類都有value屬性console.log($(":text").val());// 替換掉原來的值console.log($(":text").val("把你的大名換掉"));console.log($(":text").next().val()); // div本身沒有value屬性,所以取不到// css 修改樣式// css都是一個個鍵值對,第一個參數(shù)是屬性,第二個參數(shù)是值$("div").css("color","red");// 如果想設(shè)置多個樣式可以用字典的方式做$("div").css({"color":"red","background-color":"green"});</script> </body> </html> 示例jQuery循環(huán)
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>Title</title> </head> <body><p>哦哦哦哦哦</p><p>哦哦哦哦哦</p><p>哦哦哦哦哦</p><p>哦哦哦哦哦</p><p>哦哦哦哦哦</p><script src="jquery-3.3.1.js"></script><script>arr = [11,22,33,44,55];//jQuery的循環(huán)方式1// $.each(obj:遍歷對象; callback:就是函數(shù))// function(x,y):兩個參數(shù),x:表示索引,y:表示索引對應(yīng)的值$.each(arr,function (x,y) {console.log(x);console.log(y);});//jQuery的循環(huán)方式二,也是最常用的方式// 原理:// 1. 通常都是先拿到一個要遍歷的標(biāo)簽對象集合,$("p"):即先找到要遍歷的標(biāo)簽集合// 2. 然后對該集合里的標(biāo)簽進行遍歷: .each(function(){}),這個each里就只有一個參數(shù)了,直接寫function就行// 因為要遍歷的對象是$("p")已經(jīng)在前面了,each就是對它進行遍歷的,所有只有一個參數(shù)//.each其實就已經(jīng)對拿到的標(biāo)簽集合進行了處理,所以接下來關(guān)鍵的就是如何表示每一個標(biāo)簽,如何對遍歷到的每個標(biāo)簽進行處理// 答案就是強大的this, $(this)就表示遍歷到的標(biāo)簽集合里你當(dāng)前要操作的標(biāo)簽;$("p").each(function () {// $(this) 就是用來表示集合$("p")里每一個標(biāo)簽,console.log($(this)) //$(this) 就代表當(dāng)前的標(biāo)簽對象$(this).html("<h1>把哦哦哦哦哦改成嘎嘎嘎嘎嘎</h1>")})// JQuery和js可以混搭著用// for(var i = 0; i<arr.length;i++){// $("p").eq(i).html(arr[i])// }</script> </body> </html> jQuery的兩種循環(huán)方式 <!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>Title</title> </head> <body><button οnclick="selectAll()">全選</button><button οnclick="reverse()">反選</button><button οnclick="cancle()">取消</button><table border="1px"><tr ><td><input type="checkbox"></td><td>111</td><td>111</td><td>111</td></tr><tr ><td><input type="checkbox"></td><td>222</td><td>222</td><td>222</td></tr><tr ><td><input type="checkbox"></td><td>333</td><td>333</td><td>333</td></tr></table><script src="jquery-3.3.1.js"></script><script>// 還是要先綁定一個函數(shù),這個綁定方式還是按照js的綁定方式走的// 全選function selectAll() {// 在函數(shù)內(nèi)部用jQuery進行遍歷,然后把checked屬性改為true$(":checkbox").each(function () {$(this).prop("checked",true)})}//反選function reverse() {$(":checkbox").each(function () {if ($(this).prop("checked")){$(this).prop("checked",false)}else{$(this).prop("checked",true)}})}// 取消function cancle() {$(":checkbox").each(function () {$(this).prop("checked",false)})}</script></body> </html> jQuery之正反選實例?模態(tài):
就是執(zhí)行一個操作,彈出一個透明頁遮擋,讓透明頁底部的元素不可操作,透明頁上面的元素可以操作
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>Title</title><style>.content{height: 1800px;background-color: antiquewhite;}.shade{position: fixed;/*占滿屏,設(shè)置下面四個參數(shù)為0*/top:0;left:0;right: 0;bottom:0;background-color: gray;opacity: 0.7; /*透明度*/}.model{width:200px;height: 200px;background-color: bisque;border: #FF0000;/*居中*/position: absolute;top:50%;left: 50%;margin-top: -100px;margin-left: -100px;}.hide{display: none;}</style> </head> <body><!-- 第一層:正常顯示的網(wǎng)頁內(nèi)容--><div class="content"><button οnclick="show(this)">show</button></div><!--第二層:遮擋層:是有透明度的,且固定住不可讓content內(nèi)容再上下滑動了--><div class="shade hide"></div><!--第三層:點擊show后顯示在最上面的對話框--><div class="model hide"><button οnclick="cancle(this)">取消</button></div><script src="jquery-3.3.1.js"></script><script>function show(self) {$(self).parent().siblings().removeClass("hide")}function cancle(self) {// 方式1:鏈?zhǔn)綄ふ曳ú僮?/span>$(self).parent().addClass("hide").prev().addClass("hide");// 方式2:先找到當(dāng)前元素的父級,再找到父級的父級,然后父級下面的子級里有shade屬性的標(biāo)簽,執(zhí)行操作$(self).parent().parent().children(".models,.shade").addClass("hide")}</script></body> </html> 模態(tài)實例4.2 文檔處理
用于處理節(jié)點的增刪改查
//創(chuàng)建一個標(biāo)簽對象$("<p>")//內(nèi)部插入 -- 插入的對象變成了兒子append是加到當(dāng)前標(biāo)簽下面$("").append(content|fn) ----->$("p").append("<b>Hello</b>"); 就是把append里的內(nèi)容添加到前面的對象($("p"))里面去,= 給前面的對象加了個兒子$("").appendTo(content) ----->$("p").appendTo("div"); 與append功能完全一樣,只是寫法不同,按正常順序往下寫的;將$("p")追加到"div"的下面prepend是加到當(dāng)前標(biāo)簽的上面
$("").prepend(content|fn) ----->$("p").prepend("<b>Hello</b>");將對象添加到$("p")的前面;$("").prependTo(content) ----->$("p").prependTo("#foo");//外部插入 -- 插入的對象變成了兄弟, 原理類似 上面的內(nèi)部插入 $("").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])//復(fù)制 $("").clone([Even[,deepEven]]) <!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>Title</title> </head> <body><div class="c1"><p>P級父標(biāo)簽</p></div><button class="b1">add</button><script src="jquery-3.3.1.js"></script><script>// append 內(nèi)部插入 ---插入到下面// 點擊add 按鈕,給p標(biāo)簽下面添加一個 h1標(biāo)簽// 先找到button標(biāo)簽,給綁定一個click事件,然后給click事件一個函數(shù),執(zhí)行某功能$("button").click(function () {var $ele = $("<h1></h1>"); // 定義一個jquery變量,令該變量是一個h1標(biāo)簽;通變量寫活了$ele.html("Hello World").css("color","red"); // 給該標(biāo)簽對象賦值 $(".c1").append($ele); // 將$els對象添加到 p級標(biāo)簽的下面// appendTo :將要添加的對象$ele添加到".c1"的下面,按順序?qū)?#xff0c;更好看懂// 實現(xiàn)的功能與append是完全一樣的,只是寫法不同$ele.appendTo(".c1");});// prepend 內(nèi)部插入--插入到上面// 點擊add 按鈕,給p標(biāo)簽下面添加一個 h1標(biāo)簽// 先找到button標(biāo)簽,給綁定一個click事件,然后給click事件一個函數(shù),執(zhí)行某功能$(".b1").click(function () {var $ele1 = $("<h1></h1>"); // 定義一個jquery變量,令該變量是一個h1標(biāo)簽;通變量寫活了$ele1.html("加到當(dāng)前標(biāo)簽的上面").css("color","green"); // 給該標(biāo)簽對象賦值 $(".c1").prepend($ele1); // 將$els對象添加到 p級標(biāo)簽的下面 $ele1.prependTo(".c1");});// 第二種方式,直接append,只不過寫死了$(".c1").append("<h2>直接添加h2標(biāo)簽</h2>").css("color","green");</script> </body> </html> 內(nèi)部插入示例append, prepend <!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>Title</title> </head> <body><div class="c1"><p>P級父標(biāo)簽</p></div><button class="b1">add</button><script src="jquery-3.3.1.js"></script><script>// after 外部插入 ---插入到當(dāng)前對象的下面,變成了二弟 $("button").click(function () {var $ele = $("<h1></h1>");$ele.html("插入到當(dāng)前對象的下面,變成了二弟").css("color","red");// 插入方式1$(".c1").after($ele);// 插入方式2// $ele.insertAfter(".c1"); });// before 外部插入--插入到當(dāng)前對象的上面,變成了大哥 $(".b1").click(function () {var $ele1 = $("<h1></h1>");$ele1.html("插入到當(dāng)前對象的上面,變成了大哥").css("color","green");// $(".c1").before($ele1); $ele1.insertBefore(".c1");});</script> </body> </html> 外部插入before,after <!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>Title</title> </head> <body><div class="c1"><p>P級父標(biāo)簽</p></div><button class="b1">add</button><script src="jquery-3.3.1.js"></script><script>$(".b1").click(function () {var $ele1 = $("<h1></h1>");$ele1.html("替換掉P標(biāo)簽").css("color","green");$(".c1").replaceWith($ele1);});</script> </body> </html> 替換:replaceWith <!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>Title</title> </head> <body><div class="c1"><p>P級父標(biāo)簽</p><h1>h1能清空嗎</h1></div><button class="b1">刪除</button><script src="jquery-3.3.1.js"></script><script>$(".b1").click(function () {// empty:h1這個當(dāng)前標(biāo)簽還在,只是下面的p標(biāo)簽沒了$(".c1 h1").empty();// remove:c1這個當(dāng)前標(biāo)簽也被刪除了$(".c1").remove();});</script> </body> </html> 刪除和清空:empty和remove <!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>Title</title> </head> <body><div class="c1"><p>P級父標(biāo)簽</p><h1>h1能清空嗎</h1></div><button class="b1">復(fù)制</button><script src="jquery-3.3.1.js"></script><script>$(".b1").click(function () {$(".c1").clone().insertAfter(".c1")});</script> </body> </html> 復(fù)制:clone
但是,這個clone有個問題,執(zhí)行添加多次,是成倍的復(fù)制的,下面的示例來解決這個問題
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>Title</title> </head> <body><div class="outer"><div class="item"><button οnclick="clone_obj(this)"> + </button><input type="text"></div></div><script src="jquery-3.3.1.js"></script><script>function conle_obj(self) {// 定義個變量,通過this可以找到本標(biāo)簽,然后找到本標(biāo)簽的父級item,復(fù)制var $conle_object = $(self).parent().clone();// 然后將復(fù)制的標(biāo)簽插入到.outer的下面$conle_object.insertAfter(".outer");};</script> </body> </html> 解決成倍復(fù)制的問題新需求:讓新復(fù)制的變成減號,點擊減號可以刪除標(biāo)簽
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>Title</title> </head> <body><div class="outer"><div class="item"><button οnclick="clone_obj(this)"> + </button><input type="text"></div></div><script src="jquery-3.3.1.js"></script><script>function clone_obj(self) {// 1.定義個變量,通過this可以找到本標(biāo)簽,然后找到本標(biāo)簽的父級item,復(fù)制var $conle_object = $(self).parent().clone();// 2. children("button").html("-")是找到子標(biāo)簽然后改成 -// attr("onclick","remove_obj(this)") 是添加一個onclick點擊屬性,屬性名remove_obj(this)$conle_object.children("button").html("-").attr("onclick","remove_obj(this)");// 3. 然后再把該對象添加到.outer下面$conle_object.appendTo(".outer");};// 4.點擊減號的時候可以刪除function remove_obj(self){$(self).parent().remove()}</script> </body> </html> 可以復(fù)制,也可以remove4.3 css操作
CSS$("").css(name|pro|[,val|fn])位置$("").offset([coordinates]):標(biāo)簽相當(dāng)于視口(當(dāng)前窗口)的偏移量$("").position():相對于已經(jīng)定位了的父標(biāo)簽的偏移量$("").scrollTop([val]):scrollTop:表示舉例頂部的距離$("").scrollLeft([val])尺寸$("").height([val|fn]):拿到的就是內(nèi)容的高度,還可以改值,比如加上參數(shù):height("300px"),高度就變成了300px了$("").width([val|fn]):拿到的是內(nèi)容的寬度$("").innerHeight():拿到的是包括了padding,沒包括boder的$("").innerWidth()$("").outerHeight([options]):拿到的是包括了padding和boder的;如果再加個options 為 true的參數(shù),就會包括margin了$("").outerWidth([options]) <!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>Title</title><style>/* 將 body的邊距設(shè)置位0 */body{margin: 0px;padding: 0px;}.div1,.div2{height: 200px;width: 200px;}.div1{background-color: red;}.div2{background-color: rebeccapurple;}</style></head> <body><div class="div1"></div><div class="div2"></div><script src="jquery-3.3.1.js"></script><script>// offset 和 position都只有兩個方法:top 和 left// offset方法的參照對象都是當(dāng)前視口(能看見的窗口)console.log($(".div1").offset().top);console.log($(".div1").offset().left);// position的參數(shù)對象是已經(jīng)定位了的父級標(biāo)簽// 該示例中,它的父級標(biāo)簽就是body,body默認(rèn)就是已經(jīng)定位了的console.log($(".div2").position().top);console.log($(".div2").position().left);</script> </body> </html> 位置:offset和position <!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>Title</title><style>/* 將 body的邊距設(shè)置位0 */body{margin: 0px;padding: 0px;}.div1,.div2{height: 200px;width: 200px;}.div1{background-color: red;}.div2{background-color: rebeccapurple;}.outer{position: relative;height: 400px;width: 400px;background-color: green;}</style></head> <body><div class="div1"></div><div class="outer"><div class="div2"></div></div><script src="jquery-3.3.1.js"></script><script>// offset 和 position都只有兩個方法:top 和 left// offset方法的參照對象都是當(dāng)前視口(能看見的窗口)console.log($(".div1").offset().top);console.log($(".div1").offset().left);// position的參數(shù)對象是已經(jīng)定位了的父級標(biāo)簽// 該示例中,它的父級標(biāo)簽就是outer,outer已經(jīng)定位了// 所以此時,再看他的位置,就是相對于outer來說的,變成了0,0console.log($(".div2").position().top);console.log($(".div2").position().left);</script> </body> </html> 位置:position相對于已經(jīng)定位的父級標(biāo)簽標(biāo)簽 <!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>Title</title><style>/* 將 body的邊距設(shè)置位0 */body{margin: 0px;padding: 0px;}.div1,.div2{height: 200px;width: 200px;}.div1{background-color: red;border: 6px solid black;padding: 20px;margin: 3px;}.div2{background-color: rebeccapurple;}.outer{position: relative;height: 400px;width: 400px;background-color: green;}</style></head> <body><div class="div1"></div><div class="outer"><div class="div2"></div></div><script src="jquery-3.3.1.js"></script><script>// height: 拿到的就是內(nèi)容的大小 --- 用的最多// innerHeight: 取出的是帶著padding的大小// outerHeight: 取出的是帶著padding 和 boder的大小 console.log($(".div1").height()); // 200console.log($(".div1").height("300px")); // 340 可以改值console.log($(".div1").innerHeight()); // 240console.log($(".div1").outerHeight()); // 252console.log($(".div1").outerHeight(true)); // 258 加上參數(shù)true,就包括了外邊距margin了。</script> </body> </html> 尺寸示例
實例:返回頂部
需求:
1. 出現(xiàn)滾動條;2;隨著滾動條的下滑,底部出現(xiàn)"返回頂部",點擊頁面滾動條返回到頂部
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>Title</title><style>.div1,.div2{height: 2000px;width: 100%;}.div1{background-color: red;}.div2{background-color: rebeccapurple;}/*讓返回頂部固定到右下角*/.return-to-top{width: 80px;height: 50px;position: fixed;right: 20px;bottom: 20px;background-color: bisque;line-height: 50px;text-align: center;}/*隱藏某個標(biāo)簽,給它加個hide 屬性,然后display =none 這都是套路*/.hide{display: none;}</style></head> <body><div class="div1"></div><div class="outer"><div class="div2"></div></div><div class="return-to-top hide" οnclick="returnTop()">返回頂部</div><script src="jquery-3.3.1.js"></script><script>// window.onscroll 通過窗口的onscrool屬性來監(jiān)聽滾動事件 window.onscroll = function f() {// 可以看到滾動條當(dāng)前的位置與窗口頂部的舉例 console.log($(window).scrollTop());// 滾動條滑動過程中才出現(xiàn)返回頂部,默認(rèn)不顯示返回頂部// 需要用到判斷// $(window).scrollTop()得到的是距離窗口頂部的距離,是一個具體的值// 當(dāng)該值>800時,將hide屬性移除,就顯示了返回頂部if ($(window).scrollTop()>800){$(".return-to-top").removeClass("hide")}// 當(dāng)該值小于800時,就添加hide屬性,返回頂部就隱藏了else {$(".return-to-top").addClass("hide")}};function returnTop() {//以window為作為當(dāng)前窗口,是個參照物;事件監(jiān)聽對象// scrollTop(0):表示舉例window窗口頂部距離為0// 這樣就實現(xiàn)了點擊返回頂部的功能$(window).scrollTop(0)}</script> </body> </html> 返回頂部實例 <!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>Title</title><style>.div1,.div2{height: 2000px;width: 100%;}/*overflow: auto表示內(nèi)容填充滿后會自動產(chǎn)生一個滾動條,而不會再溢出內(nèi)容 */.div1{background-color: red;height: 300px;width: 300px;overflow: auto;}.div2{background-color: rebeccapurple;}/*讓返回頂部固定到右下角*/.return-to-top{width: 80px;height: 50px;position: fixed;right: 20px;bottom: 20px;background-color: bisque;line-height: 50px;text-align: center;}/*隱藏某個標(biāo)簽,給它加個hide 屬性,然后display =none 這都是套路*/.hide{display: none;}</style></head> <body><div class="div1"><p>111</p><p>111</p><p>111</p><p>111</p><p>111</p><p>111</p><p>111</p><p>111</p><p>111</p><p>111</p><p>111</p><p>111</p><p>111</p><p>111</p><p>111</p><p>111</p><p>111</p><p>111</p><p>111</p><p>111</p><p>111</p><p>111</p><p>111</p><p>111</p><p>111</p><p>111</p><p>111</p><p>111</p><p>111</p><p>111</p></div><div class="outer"><div class="div2"><button class="return-top" οnclick="returnTop()">returntop</button></div></div><script src="jquery-3.3.1.js"></script><script>// 監(jiān)聽局部div1,讓一點returntop button,就返回頂部function returnTop() {//$(".div1"):要監(jiān)聽哪個,就找哪個,不一定非得是監(jiān)聽Window$(".div1").scrollTop(0)}</script> </body> </html> 監(jiān)聽div,返回頂部?
五 事件頁面載入
頁面載入
ready(fn) //當(dāng)DOM載入就緒可以查詢及操縱時綁定一個要執(zhí)行的函數(shù)。頁面載入語法1:
$(document).ready(function(){
函數(shù)代碼
})
頁面載入語法2:是語法一的簡寫方式:
$(function(){
函數(shù)代碼
})事件委托(.on)---終極版的綁定方法$("").on(eve,[selector],[data],fn) // 在選擇元素上綁定一個或多個事件的事件處理函數(shù)。// .on的selector參數(shù)是篩選出調(diào)用.on方法的dom元素的指定子元素,如:// $('ul').on('click', 'li', function(){console.log('click');})就是篩選出ul下的li給其綁定click事件;
// 語法解析:就是給ul標(biāo)簽綁定了click事件,然后ul把這個事件委托給它下面的所有l(wèi)i標(biāo)簽,使所有l(wèi)i標(biāo)簽都具有click的事件
[selector]參數(shù)的好處:好處在于.on方法為動態(tài)添加的元素也能綁上指定事件;如://$('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');}方式綁定,然后動態(tài)添加//li:$('ul').append('<li>js new li<li>');這個新生成的li被綁上了click事件 [data]參數(shù)的調(diào)用: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>111</li><li>222</li><li>333</li><li>444</li><li>555</li></ul><script src="jquery-3.3.1.js"></script><script>// 在js里找到li標(biāo)簽,沒法直接按照下面的方式用,需要遍歷后才能用// var eles = document.getElementsByTagName("li");// eles.onclick = function () {// alert(123)// }// 來看看jquery的方便之處// ul,li標(biāo)簽都沒有綁定任何事件// 1. 下面看Jquer的事件綁定————簡寫方式// 用jquery綁定事件,就已經(jīng)幫你做了內(nèi)部遍歷了$("ul li").click(function () {alert("Jquety之事件綁定簡寫方式")});// 2.事件綁定的完整寫法// 上面的簡寫方式如果寫完整了就是下面的樣子,把click 和 function作為參數(shù)傳遞進去// 首先還是得先找到要綁定的標(biāo)簽$("ul li").bind("click",function () {alert("Jquety之事件綁定的完整寫法")});// 3. 有事件綁定,就有事件解綁$("ul li").unbind("click");</script> </body> </html> 事件綁定示例 <!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>Title</title></head> <body><ul><li>111</li><li>222</li><li>333</li><li>444</li><li>555</li></ul><button>add</button><script src="jquery-3.3.1.js"></script><script>// 事件綁定 --- 平時就用事件綁定就夠了$("ul li").click(function () {alert("Jquety之事件綁定簡寫方式")});// on:事件委托// 但是上面新增的標(biāo)簽卻沒有點擊事件,只是把標(biāo)簽加上了而已,如何才能動態(tài)給新增的標(biāo)簽也綁定事件呢?// 用事件委托的方式解決這個問題----用 on方法// on(第一個參數(shù)是事件,此例子是click事件,第二個參數(shù)是對誰起作用,本利是li標(biāo)簽,第三個參數(shù)是具體的函數(shù))// 這個事件委托本質(zhì)就是給ul綁定了一個事件,然后ul把這個事件委托給了ul下面的所有的li,這個時候,其實主語就變成了ul// 遇到動態(tài)綁定,就需要用到事件委托了$("ul").on("click","li",function () {alert("Jquety之事件委托方式")});// 給button標(biāo)簽綁定事件,一點擊就新增衣蛾li標(biāo)簽,并數(shù)字也變化$("button").click(function () {// 1. 先創(chuàng)建一個li標(biāo)簽var $eli = $("<li>");// 2. 獲取li標(biāo)簽的長度var len = $("ul li").length;// 3. 給新增的li標(biāo)簽加1再*1111,用來作為新增的li標(biāo)簽的文本$eli.html((len+1)*111);// 4. 然后將li標(biāo)簽添加到ul里去$eli.appendTo("ul");})</script> </body> </html> on:事件委托 <!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>Title</title><script src="jquery-3.3.1.js"></script><script>// 如果直接把jquery放到head里,這個功能就無法生效,因為上面的加載完了,下面的body的代碼還沒加載完,找不到 "ul li"// $("ul li").html(5)// 所以就引入一個頁面載入,等所有頁面就加載完成后再執(zhí)行函數(shù)// 1. 完整寫法方式$(document).ready(function () {$("ul li").html(5)});// 2. 頁面加載簡寫方式$(function () {$("ul li").html(5)})</script></head> <body><ul><li>111</li><li>222</li><li>333</li><li>444</li><li>555</li></ul><button>add</button></body> </html> 頁面載入完整寫法和簡寫
?
六 動畫效果
1. 顯示與隱藏?
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>動畫效果-顯示與隱藏</title> </head> <body><div>hello</div><button οnclick="f1()">顯示</button><button οnclick="f2()">隱藏</button><button οnclick="f3()">切換</button><script src="jquery-3.3.1.js"></script><script>function f1() {// $("div").show(); // 點擊就可以顯示div$("div").show(1000) // 點擊就可以顯示div,參數(shù)表示的毫秒,慢慢顯示 }function f2() {// $("div").hide() // 點擊就可以隱藏div$("div").hide(1000) // 點擊就可以隱藏div,參數(shù)表示的是毫秒,可以實現(xiàn)慢慢隱藏的效果 }// toggle()方法,一個方法可以實現(xiàn)上面兩個功能,會自己判斷,// 如果div是隱藏的,點擊就會顯示;如果div是顯示的,點擊就會隱藏function f3() {$("div").toggle(1000)}</script> </body> </html> 顯示與隱藏 show hide2. 滑動
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>Title</title><script src="jquery-3.3.1.js"></script><script>$(document).ready(function(){// 找到div給它綁定一個click事件$("#slideDown").click(function(){$("#content").slideDown(1000); // 向上滑動 });$("#slideUp").click(function(){$("#content").slideUp(1000); // 向下滑動 });$("#slideToggle").click(function(){$("#content").slideToggle(1000); // 自己判斷是向上滑還是向下滑;根據(jù)需求決定是否加參數(shù),表示時間 })});</script><style>#content{text-align: center;background-color: lightblue;border:solid 1px red;display: none;padding: 50px;}</style> </head> <body><div id="slideDown">出現(xiàn)</div><div id="slideUp">隱藏</div><div id="slideToggle">toggle</div><div id="content">helloworld</div></body> </html> 滑動 sliddeUp slideDown slideToggle3.淡入淡出
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>淡入淡出</title><style>.div1{width: 80px;height: 80px;background-color: #FF0000;}</style><script src="jquery-3.3.1.js"></script><script>$(document).ready(function () {$("#in").click(function () {$(".div1").fadeIn(2000)});$("#out").click(function () {$(".div1").fadeOut(2000)});$("#switch").click(function () {$(".div1").fadeToggle(2000)});// 淡出到某個設(shè)定的透明度為止,只有fadeTo有透明度參數(shù)$("#to").click(function () {$(".div1").fadeTo(2000, 0.4)})})</script> </head> <body><button id="in">淡入</button><button id="out">淡出</button><button id="switch">切換</button><button id="to">fadeto</button><div class="div1"></div></body> </html> 淡入淡出fadeIn fadeOut fadeToggle fadeTo4.回調(diào)函數(shù)
python里的回調(diào)函數(shù)就是callback
所謂回調(diào)函數(shù):就是完成了一個動作之后再去執(zhí)行某個內(nèi)容
比如上面的淡出動畫效果完成后,在執(zhí)行一個回調(diào)函數(shù),彈出alert
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>淡入淡出</title><style>.div1{width: 80px;height: 80px;background-color: #FF0000;}</style><script src="jquery-3.3.1.js"></script><script>$(document).ready(function () {$("#in").click(function () {$(".div1").fadeIn(2000)});$("#out").click(function () {// 淡出效果2秒鐘完成后,再執(zhí)行回調(diào)函數(shù)function,彈出alert$(".div1").fadeOut(2000,function () {alert("1234")})});$("#switch").click(function () {$(".div1").fadeToggle(2000)});// 淡出到某個設(shè)定的透明度為止,只有fadeTo有透明度參數(shù)$("#to").click(function () {$(".div1").fadeTo(2000, 0.4)})})</script> </head> <body><button id="in">淡入</button><button id="out">淡出</button><button id="switch">切換</button><button id="to">fadeto</button><div class="div1"></div></body> </html> 回調(diào)函數(shù)七 擴展方法 (插件機制)
一 用JQuery寫插件時,最核心的方兩個方法
<script>$.extend(object) //為JQuery 添加一個靜態(tài)方法。 $.fn.extend(object) //為JQuery實例添加一個方法。 // jQuery.extend 也可以寫成 $.extendjQuery.extend({min: function(a, b) { return a < b ? a : b; }, // 三元表達式:如果a<b,返回a,否則返回 bmax: 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>二 定義作用域
????? 定義一個JQuery插件,首先要把這個插件的代碼放在一個不受外界干擾的地方。如果用專業(yè)些的話來說就是要為這個插件定義私有作用域。外部的代碼不能直接訪問插件內(nèi)部的代碼。插件內(nèi)部的代碼不污染全局變量。在一定的作用上解耦了插件與運行環(huán)境的依賴。
(function(a,b){return a+b})(3,5)(function ($) { })(jQuery); //相當(dāng)于var fn = function ($) { };fn(jQuery);三 默認(rèn)參數(shù)
定義了jQuery插件之后,如果希望某些參數(shù)具有默認(rèn)值,那么可以以這種方式來指定
/step01 定義JQuery的作用域 (function ($) {//step03-a 插件的默認(rèn)值屬性var defaults = {prevId: 'prevBtn',prevText: 'Previous',nextId: 'nextBtn',nextText: 'Next'//…… };//step06-a 在插件里定義方法var showLink = function (obj) {$(obj).append(function () { return "(" + $(obj).attr("href") + ")" });}//step02 插件的擴展方法名稱$.fn.easySlider = function (options) {//step03-b 合并用戶自定義屬性,默認(rèn)屬性var options = $.extend(defaults, options);//step4 支持JQuery選擇器//step5 支持鏈?zhǔn)秸{(diào)用return this.each(function () {//step06-b 在插件里定義方法showLink(this);});} })(jQuery); View Code參考博客:http://www.cnblogs.com/xcj26/p/3345556.html
八 經(jīng)典實例練習(xí)
實例之注冊驗證
<form class="Form"><p><input class="v1" type="text" name="username" mark="用戶名"></p><p><input class="v1" type="text" name="email" mark="郵箱"></p><p><input class="v1" type="submit" value="submit" οnclick="return validate()"></p></form><script src="jquery-3.1.1.js"></script> <script>// 注意:// DOM對象--->jquery對象 $(DOM)// jquery對象--->DOM對象 $("")[0]//---------------------------------------------------------// DOM綁定版本function validate(){flag=true;$("Form .v1").each(function(){$(this).next("span").remove();// 防止對此點擊按鈕產(chǎn)生多個span標(biāo)簽var value=$(this).val();if (value.trim().length==0){var mark=$(this).attr("mark");var ele=document.createElement("span");ele.innerHTML=mark+"不能為空!";$(this).after(ele);$(ele).prop("class","error");// DOM對象轉(zhuǎn)換為jquery對象flag=false;// return false-------->引出$.each的return false注意點 }});return flag}//--------------------------------------------------------- //---------------------------------------------------------//---------------------------------------------------------function f(){for(var i=0;i<4;i++){if (i==2){return}console.log(i)}}f(); // 這個例子大家應(yīng)該不會有問題吧!!! //------------------------------------------li=[11,22,33,44];$.each(li,function(i,v){if (v==33){return ; // ===試一試 return false會怎樣? }console.log(v)});//------------------------------------------// $.MyEach(obj,function(i,v){}):for(var i in obj){func(i,obj[i]) ; // i就是索引,v就是對應(yīng)值// {}:我們寫的大括號的內(nèi)容就是func的執(zhí)行語句; }// 大家再考慮: function里的return只是結(jié)束了當(dāng)前的函數(shù),并不會影響后面函數(shù)的執(zhí)行//本來這樣沒問題,但因為我們的需求里有很多這樣的情況:我們不管循環(huán)到第幾個函數(shù)時,一旦return了,//希望后面的函數(shù)也不再執(zhí)行了!基于此,jquery在$.each里又加了一步:for(var i in obj){ret=func(i,obj[i]) ;if(ret==false){return ;}}// 這樣就很靈活了:// <1>如果你想return后下面循環(huán)函數(shù)繼續(xù)執(zhí)行,那么就直接寫return或return true// <2>如果你不想return后下面循環(huán)函數(shù)繼續(xù)執(zhí)行,那么就直接寫return false// ---------------------------------------------------------------------// 說了這么多,請問大家如果我們的需求是:判斷出一個輸入有問題后面就不判斷了(當(dāng)然也就不顯示了),// 怎么辦呢?// 對了if (value.trim().length==0){//...//...//flag=false; // flag=false不要去,它的功能是最后如果有問題,不提交數(shù)據(jù)!return false}//最后,大家嘗試著用jquery的綁定來完成這個功能! $(".Form :submit").click(function(){});</script> View Code輪播圖練習(xí)
.outer{width: 520px;height: 280px;margin: 80px auto;position: relative; /*relative相對定位加上后,才會按照父親本身的盒子居中定位*/ }/*.img其實不需要什么樣式,關(guān)鍵是它下面的圖片需要樣式, 每張圖片都按照父親進行絕對定位,定位的時候都疊加到一起*/ .img li{position: absolute;list-style: none; /*把li的樣式給去掉*/top: 0;left: 0; }.num{position: absolute;bottom: 10px;left: 30%; /*居中*/list-style: none; }.num li {display: inline-block;width: 18px;height: 18px;background-color: white;border-radius: 50%; /*設(shè)置成圓球*/text-align: center;line-height: 18px;margin-left: 14px; /*每個li之間的間距*/font-size: 0; /*把字體大小設(shè)置為0,就不顯示1,2,3,4*/}.btn{position: absolute; /*加上就能看見了*/top: 110px; /*舉例盒子頂部的一半140px- btn的一半30px, 就能實現(xiàn)居中*/width: 30px;height: 60px;background-color: lightgray;color: white;text-align: center;/*左右居中*/line-height: 55px;/*上下居中*/font-size: 30px;opacity: 0.6; /*透明度*/display: none; /*默認(rèn)不顯示左右切換箭頭*/}.left{left: 0; }.right{right: 0; }/*鼠標(biāo)懸浮在圖片上的時候,左右的切換箭頭顯示*/ .outer:hover .btn{display: block; }.num .active{background-color: #FF0000; } css樣式 <!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><script src="jquery-3.1.1.js"></script><title>Title</title><link rel="stylesheet" href="css/lunbo.css"></head> <body><div class="outer"><ul class="img"><li><a href=""><img src="img/1.jpg" alt=""></a></li><li><a href=""><img src="img/2.jpg" alt=""></a></li><li><a href=""><img src="img/3.jpg" alt=""></a></li><li><a href=""><img src="img/4.jpg" alt=""></a></li></ul><ul class="num"><li class="active"></li><!--空的,下面可以實現(xiàn)動態(tài)添加--><!--<li>1</li>--><!--<li>2</li>--><!--<li>3</li>--><!--<li>4</li>--></ul><div class="left btn"> < </div><div class="right btn"> > </div></div><script src="jquery-3.3.1.js"></script> <script>var i=0; // 通過jquery自動創(chuàng)建按鈕標(biāo)簽/*通過jquery 自動創(chuàng)建標(biāo)簽根據(jù)圖片數(shù)量實現(xiàn)動態(tài)添加num 下的li標(biāo)簽*/var img_num=$(".img li").length; /*看有多少個圖片,size 和 length都可以*/for(var j=0;j<img_num;j++){$(".num").append("<li></li>")}// 給上面循環(huán)加的li標(biāo)簽加上屬性active,進來的時候就是默認(rèn)給第一個加上active的$(".num li").eq(0).addClass("active");// 先做手動懸浮的輪播/*1. 鼠標(biāo)放在哪個圓點上,哪個圓點變紅2. 對應(yīng)的圖片也顯示出來*/ // 手動輪播/*給num下的li綁定事件*/$(".num li").mouseover(function () {i=$(this).index();$(this).addClass("active").siblings().removeClass("active");// 當(dāng)鼠標(biāo)懸浮在小圓點上的時候,對應(yīng)的圖片展示出來// 方法一:show(), hide()// $(".img li").eq(index).show():通過索引找到對應(yīng)的圖片,讓他顯示出來// .siblings().hide() 讓該索引對應(yīng)的其他兄弟姐妹圖片都隱藏// $(".img li").eq(index).show().siblings().hide();// $(".img li").eq(index).show(1000).siblings().hide(); // 有個特殊展開的效果// 方法二:淡入淡出// 道理同上// 但是這個有個小bug,如果快速在小圓點滑動多次停下,然后圖片還在那里不停的閃爍// $(".img li").eq(index).fadeIn(1000).siblings().fadeOut();// 解決辦法:加個stop// 意思是當(dāng)鼠標(biāo)懸浮在哪個小圓點時,其他的效果全部停止,然后執(zhí)行淡入,或者淡出效果$(".img li").eq(i).stop().fadeIn(200).siblings().stop().fadeOut(200)});// 自動輪播// 自動輪播// 設(shè)置一個定時器 c, 每隔1500毫秒,執(zhí)行一次GO_R函數(shù)var c=setInterval(GO_R,1500);function GO_R() {if(i==img_num-1){i=-1}i++;$(".num li").eq(i).addClass("active").siblings().removeClass("active");$(".img li").eq(i).stop().fadeIn(1000).siblings().stop().fadeOut(1000)}function GO_L() {if(i==0){i=img_num}i--;$(".num li").eq(i).addClass("active").siblings().removeClass("active");$(".img li").eq(i).stop().fadeIn(1000).siblings().stop().fadeOut(1000)}// hover(參數(shù)一:表示懸浮是,參數(shù)二:表示沒有懸浮時) $(".outer").hover(function () {clearInterval(c)},function () {c=setInterval(GO_R,1500)});// button 加定播// 給btn加手動定播 $(".right").click(GO_R);$(".left").click(GO_L)</script> </body> </html> 輪播?
?
?
?
?
?
?
?
?
轉(zhuǎn):https://www.cnblogs.com/yuanchenqi/articles/6070667.html?
轉(zhuǎn)載于:https://www.cnblogs.com/victorm/p/9614983.html
總結(jié)
以上是生活随笔為你收集整理的第四篇 前端学习之JQuery基础的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: WPF里ItemsControl的分组实
- 下一篇: 搭建Git服务器