jQuery框架-1.jQuery基础知识
jQuery簡介
jQuery,顧名思義是JavaScript和查詢(Query),jQuery是免費(fèi)、開源的。它可以簡化查詢DOM對象、處理事件、制作動畫、處理Ajax交互過程且兼容多瀏覽器的javascript庫,核心理念是write less,do more(寫得更少,做得更多)。
jQuery優(yōu)勢
引入jQuery
版本選擇
- 1.x:兼容ie678,使用最為廣泛的,官方只做BUG維護(hù),功能不再新增。因此一般項(xiàng)目來說,使用1.x版本就可以了,最終版本:1.12.4 (2016年5月20日)
- 2.x:不兼容ie678,很少有人使用,官方只做BUG維護(hù),功能不再新增。如果不考慮兼容低版本的瀏覽器可以使用2.x,最終版本:2.2.4 (2016年5月20日)
- 3.x:不兼容ie678,只支持最新的瀏覽器。除非特殊要求,一般不會使用3.x版本的,很多老的jQuery插件不支持這個版本。目前該版本是官方主要更新維護(hù)的版本。
jQuery和$的關(guān)系:
一、jQuery選擇器
- ?ID選擇器:$(“#box”);
- 類名選擇器:$(“.box”);
- 標(biāo)簽選擇器:$(“div”);
- 后代選擇器:$(“#box? p”);
- :first:獲取第一個元素。
- :last:獲取最后一個元素。
- :even:匹配所有索引值為偶數(shù)的元素,從 0 開始計(jì)數(shù)。
- :odd:匹配所有索引值為奇數(shù)的元素,從 0 開始計(jì)數(shù)。
- :eq(index):匹配一個給定索引值的元素,從 0 開始計(jì)數(shù)。
- :not(selector):去除所有與給定選擇器匹配的元素。
- :has(selector):匹配含有選擇器所匹配的元素的元素。?
二、jQuery屬性和樣式CSS
操作屬性:
attr(name|properties|key,value|fn):設(shè)置或返回被選元素的屬性值。
removeAttr(name):從每一個匹配的元素中刪除一個屬性。
prop(name|properties|key,value|fn):獲取在匹配的元素集中的第一個元素的屬性值。
removeProp(name):用來刪除由.prop()方法設(shè)置的屬性集。
區(qū)別:attr可以操作(增刪改查)自定義的節(jié)點(diǎn)屬性,而prop不可以(增刪改查)。attr和prop對input的disabled屬性的返回值不一致,attr返回disabled或者undefined,而prop返回布爾值。?
<!DOCTYPE html> <html><head><meta charset="UTF-8"><title>屬性和css</title><style type="text/css">html,body{height:100%;}body{position:relative;overflow: hidden;}.container{height:200px;background:#ff0000;line-height: 200px;text-align: center;color: #ffffff;position:absolute;left:0;right:0;top:0;bottom:0;margin:auto;}</style></head><body><div class="container" data-save="data"><div class="box">輸入內(nèi)容:<input class="test" type="text" disabled/></div></div></body> <!--考慮兼容選擇相應(yīng)的版本,此處參考百度選擇1.x的版本進(jìn)行說明,案例不提供此文件自行下載--> <script type="text/javascript" src="js/jquery.1.8.3.js"></script> <script type="text/javascript"> // 操作屬性 // 讀取屬性值console.log($('[type=text]').attr('class'));console.log($('[type=text]').prop('class'));console.log($('[type=text]').attr('name'));//返回undefinedconsole.log($('[type=text]').prop('name'));//無返回值 console.log($('[type=text]').attr('disabled')); //返回值disabledconsole.log($('[type=text]').prop('disabled')); //返回值true // attr支持所有屬性節(jié)點(diǎn)的增刪改 prop支持自帶屬性的操作,不支持自定義屬性的操作 // 操作標(biāo)簽自帶屬性$('.container').attr('class','boxcontainer') //設(shè)置class屬性為boxcontainer$('.box').prop('class','containerClass') //設(shè)置class屬性為containerClass // 操作標(biāo)簽自定義屬性$('.containerClass').attr('data-save','update') //成功更改$('.boxcontainer').prop('data-save','update') //不起作用 // 刪除相關(guān)屬性removeAttr移除相關(guān)屬性 removeProp移除相關(guān)屬性值且賦值undefined$('.containerClass').removeAttr("class")$('.boxcontainer').removeProp("class") </script> </html>?操作Class:
addClass(class|fn) :為每個匹配的元素添加指定的類名。
removeClass([class|fn]) :從所有匹配的元素中刪除全部或者指定的類。
toggleClass(class|fn[,switch]):如果存在(不存在)就刪除(添加)一個類。?
<!DOCTYPE html> <html><head><meta charset="UTF-8"><title>屬性和css</title><style type="text/css">html,body{height:100%;}body{position:relative;overflow: hidden;}.container{width:100px;height:100px;background:#ff0000;line-height: 100px;text-align: center;color: #ffffff;position:absolute;left:0;right:0;top:0;bottom:0;margin:auto;}.changeClass{width:100px;height:100px;line-height: 100px;text-align: center;color: #ffffff;background: #000000;position:absolute;left:0;right:0;top:0;bottom:0;margin:auto;}</style></head><body><div class="container"><div class="box toggleClassOne">顯示內(nèi)容</div></div></body> <!--考慮兼容選擇相應(yīng)的版本,此處參考百度選擇1.x的版本進(jìn)行說明,案例不提供此文件自行下載--> <script type="text/javascript" src="js/jquery.1.8.3.js"></script> <script type="text/javascript"> // 操作class // 添加class // $('.container').addClass('changeClass'); // 移除class // $('.container').removeClass('changeClass'); // 鏈?zhǔn)綄懛ㄅc上面的分開效果同$('.container').addClass('changeClass').removeClass('container'); // toggleClass存在刪除不存在添加$('.box').toggleClass('toggleClassOne');$('.box').toggleClass('toggleClassTwo'); </script> </html>?操作內(nèi)容:
html([val|fn]):取得第一個匹配元素的html內(nèi)容。這個函數(shù)不能用于XML文檔。但可以用于XHTML文檔。
text([val|fn]):取得所有匹配元素的內(nèi)容。結(jié)果是由所有匹配元素包含的文本內(nèi)容組合起來的文本。這個方法對HTML和XML文檔都有效。
val([val|fn|arr]):獲得匹配元素的當(dāng)前值。如果多選,將返回一個數(shù)組,其包含所選的值。?
<!DOCTYPE html> <html><head><meta charset="UTF-8"><title>屬性和css</title><style type="text/css">html,body{height:100%;}ul{list-style: none;width: 50%;margin: 0 auto;text-align: center;}#list li{line-height: 40px;border-bottom: 1px dashed #ff0000;font-size: 20px;} </style></head><body><div class="container" data-save="data"><div class="box"><ul id="list"><li>這是1</li><li class="even">這是2</li><li>這是3</li></ul></div><input type="text" name="username" id="username"/><div class="testhtml"></div> <div class="testtext"></div></div></body> <!--考慮兼容選擇相應(yīng)的版本,此處參考百度選擇1.x的版本進(jìn)行說明,案例不提供此文件自行下載--> <script type="text/javascript" src="js/jquery.1.8.3.js"></script> <script type="text/javascript"> // 操作內(nèi)容//html標(biāo)簽文本輸出 text輸出文本console.log($('.container').html());console.log($('.container').text());//賦值時html標(biāo)簽可渲染 text當(dāng)文本處理$('.testhtml').html('<b>好詩!</b>');$('.testtext').text('<b>好詩!</b>');$('[name=username]').val('用戶名');console.log($('[name=username]').val()); </script> </html>?
操作CSS:
css(name|pro|[,val|fn]):訪問匹配元素的樣式屬性。
?
// 操作樣式(詳細(xì)請查看選擇器)console.log($('#box').css('width'));$('#box').css({'width': 250, height: 500});?操作位置:
offset([coordinates]):獲取匹配元素在當(dāng)前文檔的相對偏移。返回的對象包含兩個整型屬性:top 和 left,以像素計(jì)。方法只對可見元素有效。
position():獲取匹配元素相對父元素的偏移。返回的對象包含兩個整型屬性:top 和 left。為精確計(jì)算結(jié)果,請?jiān)谘a(bǔ)白、邊框和填充屬性上使用像素單位。此方法只對可見元素有效。
scrollTop([val]):獲取匹配元素相對滾動條頂部的偏移。此方法對可見和隱藏元素均有效。
scrollLeft([val]):獲取匹配元素相對滾動條左側(cè)的偏移。此方法對可見和隱藏元素均有效。
<!DOCTYPE html> <html><head><meta charset="UTF-8"><title>屬性和css</title><style type="text/css">html,body{height:100%;}body{position: relative;overflow: hidden;}.container{width: 300px;height: 300px;background: #ff0000;position: absolute;left: 0;right: 0;top: 0;bottom: 0;margin: auto;}.box{width: 100px;height: 100px;line-height: 100px;text-align: center;color: #ffffff;background: #000000;position: absolute;left: 0;right: 0;top: 0;bottom: 0;margin: auto;}</style></head><body><div class="container" data-save="data"><div class="box">中心</div></div><div id="outer" style="width: 200px; height: 200px; overflow: auto; border: 1px solid #ccc; padding: 10px; margin: 10px;"><div id="inner" style="height: 400px;"></div></div></body> <!--考慮兼容選擇相應(yīng)的版本,此處參考百度選擇1.x的版本進(jìn)行說明,案例不提供此文件自行下載--> <script type="text/javascript" src="js/jquery.1.8.3.js"></script> <script type="text/javascript"> //獲取相對于文檔的left和top的值console.log($('.container').offset())//設(shè)置left和top值$('.box').offset({left:0,top:0})console.log($('.box').offset())console.log($('#outer').scrollTop());$('#outer').scrollTop(50);$('#outer').scroll(function () {console.log($('#outer').scrollTop());}); </script> </html>?操作尺寸:
height([val|fn]):取得匹配元素當(dāng)前計(jì)算的高度值(px)。
width([val|fn]):取得第一個匹配元素當(dāng)前計(jì)算的寬度值(px)。
innerHeight():獲取第一個匹配元素內(nèi)部區(qū)域高度(包括補(bǔ)白、不包括邊框)。此方法對可見和隱藏元素均有效。
innerWidth():獲取第一個匹配元素內(nèi)部區(qū)域?qū)挾?#xff08;包括補(bǔ)白、不包括邊框)。此方法對可見和隱藏元素均有效。
outerHeight([options]):獲取第一個匹配元素外部高度(默認(rèn)包括補(bǔ)白和邊框)。此方法對可見和隱藏元素均有效。
outerWidth([options]):獲取第一個匹配元素外部寬度(默認(rèn)包括補(bǔ)白和邊框)。此方法對可見和隱藏元素均有效。
注:設(shè)置options為true,計(jì)算margin在內(nèi)。?
<!DOCTYPE html> <html><head><meta charset="UTF-8"><title>屬性和css</title><style type="text/css">html,body{height:100%;}</style></head><body><div id="outer" style="width: 200px; height: 200px; overflow: auto; border: 1px solid #ccc; padding: 10px; margin: 10px;"><div id="inner" style="height: 400px;"></div></div></body> <!--考慮兼容選擇相應(yīng)的版本,此處參考百度選擇1.x的版本進(jìn)行說明,案例不提供此文件自行下載--> <script type="text/javascript" src="js/jquery.1.8.3.js"></script> <script type="text/javascript"> console.log($('#outer').width(150));console.log($('#outer').height(130));// 補(bǔ)白的寬度、高度console.log($('#outer').innerWidth());console.log($('#outer').innerHeight());// 邊框和補(bǔ)白的寬度、高度console.log($('#outer').outerWidth());console.log($('#outer').outerHeight());// 外邊距、邊框和補(bǔ)白的寬度、高度console.log($('#outer').outerWidth(true));console.log($('#outer').outerHeight(true)); </script> </html>?三、過濾查找?
過濾元素:(與選擇器的作用基本相同,只是分裝成方法使用,此處不再舉例)
eq(index|-index):獲取第N個元素。這個元素的位置是從0算起,如果是負(fù)數(shù),則從集合中的最后一個元素開始倒數(shù)。
first():獲取第一個元素。
last():獲取最后一個元素。
hasClass(class):檢查當(dāng)前的元素是否含有某個特定的類,如果有,則返回true。
has(expr|ele):保留包含特定后代的元素,去掉那些不含有指定后代的元素。
not(expr|ele|fn):刪除與指定表達(dá)式匹配的元素。
查找元素:
children([expr]):取得一個包含匹配的元素集合中每一個元素的所有子元素的元素集合。只考慮子元素而不考慮所有后代元素。
find(expr|obj|ele):搜索所有與指定表達(dá)式匹配的子元素。
parent([expr]):取得一個包含著所有匹配元素的唯一父元素的元素集合。
offsetParent():返回第一個匹配元素用于定位的父節(jié)點(diǎn)。
next([expr]):取得一個包含匹配的元素集合中每一個元素緊鄰的后面同輩元素的元素集合。
nextAll([expr]):查找當(dāng)前元素之后所有的同輩元素。
prev([expr]):取得一個包含匹配的元素集合中每一個元素緊鄰的前一個同輩元素的元素集合。
prevAll([expr]):查找當(dāng)前元素之前所有的同輩元素。
siblings([expr]):取得一個包含匹配的元素集合中每一個元素的所有唯一同輩元素的元素集合。可以用可選的表達(dá)式進(jìn)行篩選。
串聯(lián)操作:
add(expr|ele|html|obj[,con]):把與表達(dá)式匹配的元素添加到j(luò)Query對象中。這個函數(shù)可以用于連接分別與兩個表達(dá)式匹配的元素結(jié)果集。返回的結(jié)果將始終以元素在HTML文檔中出現(xiàn)的順序來排序,而不再是簡單的添加。
?
<!DOCTYPE html> <html lang="zh"> <head><meta charset="UTF-8" /><title>jQuery練習(xí)-選擇器</title> </head> <body><ul id="list"><li><label>測試數(shù)據(jù)</label></li><li>測試數(shù)據(jù)</li><li class="special">測試數(shù)據(jù)</li><li>測試數(shù)據(jù)</li></ul> </body> <!--考慮兼容選擇相應(yīng)的版本,此處參考百度選擇1.x的版本進(jìn)行說明,案例不提供此文件自行下載--> <script type="text/javascript" src="js/jquery.1.8.3.js"></script> <script type="text/javascript"> $('#list .special').add('label').css('background','#ff0000'); </script> </html>?
andSelf():將先前所選的加入當(dāng)前元素中。
?
<!DOCTYPE html> <html lang="zh"> <head><meta charset="UTF-8" /><title>jQuery練習(xí)-選擇器</title> </head> <body><ul id="list"><li>測試數(shù)據(jù)</li><li>測試數(shù)據(jù)</li><li class="special">測試數(shù)據(jù)</li><li>測試數(shù)據(jù)</li></ul> </body> <!--考慮兼容選擇相應(yīng)的版本,此處參考百度選擇1.x的版本進(jìn)行說明,案例不提供此文件自行下載--> <script type="text/javascript" src="js/jquery.1.8.3.js"></script> <script type="text/javascript"> $('#list .special').nextAll().andSelf().css('background','#ff0000'); </script> </html>?end():回到最近的一個"破壞性"操作之前。即,將匹配的元素列表變?yōu)榍耙淮蔚臓顟B(tài)。如果之前沒有破壞性操作,則返回一個空集。所謂的"破壞性"就是指任何改變所匹配的jQuery元素的操作。
<!DOCTYPE html> <html lang="zh"> <head><meta charset="UTF-8" /><title>jQuery練習(xí)-end()</title> </head> <body> <ul class="first"><li class="foo">list item 1</li><li>list item 2</li><li class="bar">list item 3</li></ul><ul class="second"><li class="foo">list item 1</li><li>list item 2</li><li class="bar">list item 3</li></ul> </body> <!--考慮兼容選擇相應(yīng)的版本,此處參考百度選擇1.x的版本進(jìn)行說明,案例不提供此文件自行下載--> <script type="text/javascript" src="js/jquery.1.8.3.js"></script><script>//end() 方法結(jié)束當(dāng)前鏈條中的最近的篩選操作,并將匹配元素集還原為之前的狀態(tài)$('ul.first').find('.foo').css('background-color', 'red').end().find('.bar').css('background-color', 'green');</script> </html>四、jQuery事件?
頁面載入事件:
ready(fn):當(dāng)DOM載入就緒可以查詢及操縱時綁定一個要執(zhí)行的函數(shù)。這是事件模塊中最重要的一個函數(shù),因?yàn)樗梢詷O大地提高web應(yīng)用程序的響應(yīng)速度。簡單地說,這個方法純粹是對向window.load事件注冊事件的替代方法。?
/*DOMContenLoaded:dom結(jié)構(gòu)加載完成后調(diào)用事件;load:dom結(jié)構(gòu)加載完成后鏈接的資源加載完成后執(zhí)行;網(wǎng)頁加載的內(nèi)容越大,二者之間相差的時間越長,相對的DOMContentLoaded事件用戶體驗(yàn)更合適*///ready()方法是在DOMContenLoaded方法上封裝的 $(document).ready(function () {console.log('頁面加載完成!');});//此調(diào)用方式等同于使用ready事件,可查看jQuery源碼 $(function () {console.log('頁面加載完成!');});?綁定事件:
參數(shù)說明:
-
- events:表示jQuery事件不加on,可同時綁定多個事件,事件間用空格隔開例如:'click dbclick';
- [selector]:表示對應(yīng)樣式的選擇器;
- [data]:表示傳入回調(diào)函數(shù)的參數(shù),用event.data進(jìn)行接收
- fn:回調(diào)函數(shù)
on(events,[selector],[data],fn):在選擇元素上綁定一個或多個事件的事件處理函數(shù)。
off(events,[selector],[fn]):在選擇元素上移除一個或多個事件的事件處理函數(shù)。
bind(type,[data],fn):為每個匹配元素的特定事件綁定事件處理函數(shù)。
unbind(type,[data|fn]]):bind()的反向操作,從每一個匹配的元素中刪除綁定的事件。如果沒有參數(shù),則刪除所有綁定的事件。
one(type,[data],fn):為每一個匹配元素的特定事件(像click)綁定一個一次性的事件處理函數(shù)。
hover([over,]out):當(dāng)鼠標(biāo)移動到一個匹配的元素上面時,會觸發(fā)指定的第一個函數(shù)。當(dāng)鼠標(biāo)移出這個元素時,會觸發(fā)指定的第二個函數(shù)。
click([[data],fn]):觸發(fā)每一個匹配元素的click事件。這個函數(shù)會調(diào)用執(zhí)行綁定到click事件的所有函數(shù)。
注:其他事件方法使用方式一樣。例如:mouseover、mouseout、dblclick、change、blur、focus、keydown、keyup、keypress、mousedown、mouseup、mousemove、mouseenter、mouseleave、resize、scroll、select、submit、unload等。?
<!DOCTYPE html> <html><head><meta charset="UTF-8"><title>屬性和css</title><style type="text/css">html,body{height:100%;}ul{list-style: none;width: 50%;margin: 0 auto;text-align: center;}#list li{line-height: 40px;border-bottom: 1px dashed #ff0000;font-size: 20px;} </style></head><body><div class="container" data-save="data"><div class="box"><ul id="list"><li>這是1</li><li class="even">這是2</li><li>這是3</li><li>這是4</li><li>這是5</li><li class="even">這是6</li><li>這是7</li><li>這是8</li></ul></div></div></body> <!--考慮兼容選擇相應(yīng)的版本,此處參考百度選擇1.x的版本進(jìn)行說明,案例不提供此文件自行下載--> <script type="text/javascript" src="js/jquery.1.8.3.js"></script> <script type="text/javascript"> /* //添加單擊事件$('#list li').on('click',function(){alert(this.innerHTML);})*//* //添加雙擊事件$('#list li').on('dblclick',function(){alert(this.innerHTML);})//無法移除雙擊事件(不是同一個方法)$('#list li').off('dblclick',function(){alert(this.innerHTML);})*/function fun(){alert(0000);}/* //添加雙擊事件且可選擇選擇器過濾$('#list').on('dblclick','.even',fun);//可移除雙擊事件$('#list').off('dblclick',fun);*//* //添加雙擊事件$('#list').on('dblclick',fun);//無法移除雙擊事件與添加雙擊事件的方法選擇器對應(yīng)或者全部移除$('#list').off('dblclick','.even',fun);*//* //bind和on的區(qū)別是其無法進(jìn)行選擇器過濾,其他用法基本相同都可添加多個事件$('#list').bind('click ', fun);$('#list').unbind('click', fun);*//* //一次性事件處理函數(shù)$('#list').one('click',{'param':'參數(shù)'},function(e){console.log(e.data['param'])})*//* //鼠標(biāo)劃入劃出事件$('#list').hover(function(){console.log("鼠標(biāo)劃入")},function(){console.log("鼠標(biāo)劃出")})*/$('#list').click(function(){console.log("鼠標(biāo)點(diǎn)擊事件")}) </script> </html>附錄:
選項(xiàng)卡實(shí)例demo:?
<!doctype html> <html lang="en"> <head><meta charset="UTF-8"><title>jQuery選項(xiàng)卡效果</title><style type="text/css">*{padding: 0;margin: 0;}html,body{height: 100%;}body{background: #f4f4f4;}ul{list-style: none;}.container{width: 600px;margin: 100px auto;background: #ffffff;border-radius: 10px;border:1px solid #555555;overflow: hidden;}.header-box{}.tab-navigation{overflow: hidden;background: #eeeeee;color: #080808;border-bottom: 1px solid #555555;}.tab-navigation li{float: left;width: 100px;text-align: center;line-height: 50px;}.tab-body{width: 100%;height: 300px;position: relative; }.tab-body li{padding: 10px;position: absolute;left: 0;top: 0;}.tab-body li:first-child{display: block;} .tab-body li:nth-child(n 2){display: none;}.tab-navigation .selected{background: #ffffff;color: #000000;}.tab-navigation .active{background: #ff0000;}</style> </head> <body><div class="container"><div class="header-box"><ul class="tab-navigation"><li class="selected">選項(xiàng)卡1</li><li>選項(xiàng)卡2</li><li>選項(xiàng)卡3</li><li>選項(xiàng)卡4</li><li>選項(xiàng)卡5</li><li>選項(xiàng)卡6</li></ul> </div><div class="body-box"><ul class="tab-body"><li>內(nèi)容1內(nèi)容1內(nèi)容1內(nèi)容1內(nèi)容1內(nèi)容1內(nèi)容1內(nèi)容1內(nèi)容1內(nèi)容1內(nèi)容1</li><li>內(nèi)容2內(nèi)容2內(nèi)容2內(nèi)容2內(nèi)容2內(nèi)容2內(nèi)容2內(nèi)容2內(nèi)容2內(nèi)容2內(nèi)容2</li><li>內(nèi)容3內(nèi)容3內(nèi)容3內(nèi)容3內(nèi)容3內(nèi)容3內(nèi)容3內(nèi)容3內(nèi)容3內(nèi)容3內(nèi)容3</li><li>內(nèi)容4內(nèi)容4內(nèi)容4內(nèi)容4內(nèi)容4內(nèi)容4內(nèi)容4內(nèi)容4內(nèi)容4內(nèi)容4內(nèi)容4</li><li>內(nèi)容5內(nèi)容5內(nèi)容5內(nèi)容5內(nèi)容5內(nèi)容5內(nèi)容5內(nèi)容5內(nèi)容5內(nèi)容5內(nèi)容5</li><li>內(nèi)容6內(nèi)容6內(nèi)容6內(nèi)容6內(nèi)容6內(nèi)容6內(nèi)容6內(nèi)容6內(nèi)容6內(nèi)容6內(nèi)容6</li></ul> </div></div> </body> <script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.js"></script> <script type="text/javascript">$('.tab-navigation li').click(function () {$(this).addClass('selected').siblings().removeClass('selected')var index = $('.tab-navigation li').index(this);$('.tab-body li').eq(index).css('display','block').siblings().css('display','none');}).hover(function () {$(this).addClass('active');},function () {$(this).removeClass('active');}); </script> </html>?
更多專業(yè)前端知識,請上 【猿2048】www.mk2048.com
總結(jié)
以上是生活随笔為你收集整理的jQuery框架-1.jQuery基础知识的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: NodeJS的安装与使用
- 下一篇: 从零开始学习前端开发 — 15、CSS3