js實現封裝jQuery的簡單方法與鏈式操作詳解
我用這篇文章來理一理如何用js去實現封裝jquery的簡單方法。
本文js實現了下面jquery的幾種方法,我將它分為8個小目標
- 實現$(".box1").click( )方法
- 實現$("div").click( )方法
- 考慮$( )中引數的三種情況
- 實現jq中的on方法
- 實現鏈式操作
- 實現jq中的eq方法
- 實現jq中的end方法
- 實現jq中的css方法
有不正確的地方還望大家在評論區指出來,謝謝啦。
1. 實現$(".box1").click( )方法
首先,我們定第一個小目標,就是如何一步一步去實現下方jQuery程式碼的功能。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width,initial-scale=1.0"> <title>Document</title> //同一個檔案下操作的話,後面記得刪除下面引入的cdn <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.0/jquery.min.js"></script> <style> .box1 { width: 100px; height: 100px; background: red; } </style> </head> <body> <div class="box1"></div> </body> <script> $(".box1").click(()=>{ console.log(456); }) </script> </html> 複製程式碼
$(".box1").click(()=>{ console.log(456); })
好了,言歸正傳,我們來分析上面jQuery的程式碼。
- $(".box1") 就是實現了選擇器的功能。
- $(".box1").click 就是選擇器 + 呼叫click方法
- 最後在click裡面傳入函式。
第一個小目標就是自己封裝js來實現上面程式碼的功能。我們分三步走戰略來實現。
- js實現 $(".box1")
- 實現 $(".box1").click()
- 實現 $(".box1").click( ( ) => { console.log("123") } )
第一步就是先用js實現 $(".box1"), 對吧
// 實現$(".box1") class jquery { constructor(arg) { console.log(document.querySelector(arg)); } } function $(arg) { return new jquery(arg); } // 實現$(".box1") let res = $(".box1"); console.log(res);
這樣是不是就通過構建()方法並返回jquery例項,實現了(".box1")呢。
那好,接下來我們進行第二步就是實現 $(".box1").click()。相信大家也看出來了,就是在jquery類中多了一個click方法。
// 實現$(".box1").click() class jquery { constructor(arg) { console.log(document.querySelector(arg)); } click() { console.log("執行了click方法"); } } function $(arg) { return new jquery(arg); } // 實現$(".box1").click() let res = $(".box1").click(); console.log(res);
接下來,我們進行第三步就是實現 $(".box1").click( ( ) => { console.log("123") } )。
// 實現$(".box1").click(() => {console.log("123")}) class jquery { constructor(arg) { this.element = document.querySelector(arg); // console.log(element); } click(fn) { this.element.addEventListener("click",fn); } } function $(arg) { return new jquery(arg); } //實現$(".box1").click(() => {console.log("123")}) $(".box1").click(() => { console.log("123") });
到此為止,我們實現了第一個小目標,大家是不是覺得簡單呢,ok,接下來我們繼續第二個小目標。
2. 實現$("div").click( )方法
第二個小目標也不難,就是考慮有多個div元素需要繫結click事件,我們用selectSelectorAll來獲取元素的話,如何處理,其實也挺簡單,就是在click方法中多出一個迴圈,去獲取NodeList中的值。我直接上程式碼了,大家試一試就知道啦。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width,initial-scale=1.0"> <title>Document</title> <style> .box1 { width: 100px; height: 100px; background: red; } .box2 { width: 100px; height: 100px; background: blue; } </style> </head> <body> <div class="box1"></div> <div class="box2"></div> </body> <script> // 實現$(".box1").click(() => {console.log("123")}) class jquery { constructor(arg) { //下面element存的是NodeList物件,它是一個類陣列有length屬性 this.element = document.querySelectorAll(arg); } click(fn) { for(let i = 0; i < this.element.length; i++) { this.element[i].addEventListener("click",fn); } } } function $(arg) { return new jquery(arg); } //實現$(".box1").click(() => {console.log("123")}) $("div").click(() => { console.log("123") }); </script> </html>
好了,完成兩個小目標了,相信你已經有成就感了。
3. 考慮$( )中引數的三種情況
接下來第三個小目標 我們來考慮一下$( )中引數不同的情況,我先將三種情況列出來。(可能還有其他情況,這裡就不說了)
1.情況一:就是$( )引數為字串
$(".box1")
2.情況二:就是$( )引數為函式的情況。
//引數為函式 $(function() { console.log("123"); })
3.情況三:就是$( )引數為NodeList物件或selectSelect獲得的節點
// 情況三 $(document.querySelectorAll("div")).click(()=>{ console.log("123"); }) $(document.querySelector("div")).click(()=>{ console.log("456"); })
接下來第三個小目標是手寫函式來實現三種情況。 首先我們增加addEles方法,修改上面的click方法
addEles(eles){ for (let i = 0; i < eles.length; i++) { this[i] = eles[i]; } this.length = eles.length; } // 實現$(".box1").click(() => {console.log("123")}) click(fn) { for(let i = 0; i < this.length; i++) { this[i].addEventListener("click",fn); } }
接下來實現三種不同引數的處理方法
constructor(arg) { //情況一 if(typeof arg === 'string') { this.addEles(document.querySelectorAll(arg)); }else if(typeof arg === 'function') { //情況二 document.addEventListener("DOMContentLoaded",arg); }else { //情況三 if(typeof arg.length === 'undefined') { this[0] = arg; this.length = 1; }else { this.addEles(arg); } } }
4. 實現jq中的on方法
接下來實現第四個小目標 實現jq的on方法
// on方法
on(eventName,fn) {
let eventArray = eventName.split(" ");
//考慮多個節點
for(let i = 0; i < this.length; i++) {
//考慮多個事件
f程式設計客棧or(let j = 0; j < eventArray.length; j++) {
this[i].addEventListener(eventArray[j],fn);
}
}
}
再測試下ok不
// on方法 $("div").on("mouseover mousedown",function(){ console.log("on方法"); })
5. 實現鏈式操作
接下來實現第五個小目標 實現jq的鏈式操作
劃重點,在on和click中新增return this即可實現鏈式
//鏈式操作 //劃重點,在on和click中新增return this即可實現鏈式 // click方法 click(fn) { for(let i = 0; i < this.length; i++) { this[i].addEventListener("click",fn); } return this; // console.log(this); } // on方法 on(eventName,fn) { let eventArray = eventName.split(" "); //考慮多個節點 for(let i = 0; i < this.length; i++) { //考慮多個事件 for(let j = 0; j < eventArray.length; j++) { this[i].addEventListener(eventArray[j],fn); } } return this; }
6. 實現jq中的eq方法
接下來實現第六個小目標 實現jq中的eq方法
//eq方法 eq(index) { return new jquery(this[index]); }
這裡通過new一個jquery實現 new的過程大家應該清楚吧,我們溫習一下:
- 執行函式
- 自動建立一個空物件
- 將空物件的原型指向建構函式的prototype屬性
- 將空物件和函式內部this繫結
- 如果renturn後跟著物件,返回這個物件。沒跟的話就自動返回this物件
7. 實現jq中的end方法
實現第七個小目標 實現jq中的end方法。要實現這個功能,除了新增end( )方法,我們還得在建構函式上實現,constructor新增引數root,新增屬性prevObject,並在eq方法這種新增引數this。
constructor(arg,root) { if(typeof root === "undefined") { this.prevObject = [document]; }else { this.prevObject = root; } //eq方法 eq(index) { return new jquery(this[index],this); } //end方法 end() { return this.prevObject; }
8. 實現jq中的css方法
在jq中css可以獲取樣式,設定一個樣式或多個樣式
// 情況一 :獲取樣式 (只去獲取第一個元素) let res = $("div").css("background"); console.log(res); // 情況二 (設定樣式) $("div").css("background","yellow"); // // 情況三 (設定多個樣式) $("div").css({background:"black",width:200,opacity:0.3});
接下來實現css方法
//css方法 css(...程式設計客棧args) { if(args.length === 1) { //情況一:獲取樣式 if(typeof args[0] === 'string') { return this.getStyle(this[0],args[0]); }else { //情況三:設定多個樣式 for(let i = 0; i < this.length; i++) { for(let j in args[0]) { this.setStyle(this[i],j,args[0][j]); } } } }else { //情況三 for(let i = 0; i < this.length; i++) { this.setStyle(this[i],args[0],args[1]); } } } //css方法 css(...args) { if(args.length === 1) { //情況一:獲取樣式 if(typeof args[0] === 'string') { return this.getStyle(this[0],args[0]); }else { //情況三:設定多個樣式 for(let i = 0; i < this.length; i++) { for(let j in args[0]) { this.setStyle(this[i],args[0][j]); } } } }else { //情況三 for(let i = 0; i < this.length; i++) { this.setStyle(this[i],args[1]); } } }
增加cssNumber方法來確定不用加px的屬性名
//css方法用 $.cssNumber = { animationIterationCount: true,columnCount: true,fillOpacity: true,flexGrow: true,flexShrink: true,fontWeight: true,gridArea: true,gridColumn: true,gridColumnEnd: true,gridColumnStart: true,gridRow: true,gridRowEnd: true,gridRowStart: true,lineHeight: true,opacity: true,order: true,orphans: true,widows: true,zIndex: true,zoom: true }
最後獻上完整程式碼,如果大哥們覺的不錯,給個讚唄
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>Document</title>
<style> .box1 {
width: 100px;
height: 100px;
background: red;
}
.box2 {
width: 100px;
height: 100px;
background: blue;
transform-origin: 0 100% 0;
transition: 0.3s;
}
.box2:hover {
transform: scaleX(2);
width: 200px;
height: 100px;
} </style>
</head>
<body>
<div class="box1"></div>
<div class="box2"></div>
<button>點選</button>
</body>
<script> class jquery {
constructor(arg,root) {
if(typeof root === "undefined") {
this.prevObject = [document];
}else {
this.prevObject = root;
}
//情況一
if(typeof arg === 'string') {
this.addEles(document.querySelectorAll(arg));
}else if(typeof arg === 'function') {
//情況二
document.addEventListener("DOMContentLoaded",arg);
}else {
//情況三
if(typeof ahttp://www.cppcns.comrg.length === 'undefined') {
this[0] = arg;
this.length = 1;
}else {
this.addEles(arg);
}
}
}
//增加方法
addEles(eles){
for (let i = 0; i < eles.length; i++) {
this[i] = eles[i];
}
this.length = eles.length;
}
//鏈式操作
//劃重點,在on和click中新增return即可實現鏈式
// click方法
click(fn) {
for(let i = 0; i < this.length; i++) {
this[i].addEventListener("click",fn);
}
}
return this;
}
//eq方法
eq(index) {
return new jquery(this[index],this);
}
//end方法
end() {
return this.prevObject;
}
//css方法
css(...args) {
if(args.length === 1) {
//情況一:獲取樣式
if(typeof args[0] === 'string') {
return this.getStyle(this[0],args[0][j]);
}
}
}
}else {
//情況三
OdoIaEmcuL for(let i = 0; i < this.length; i++) {
this.setStyle(this[i],args[1]);
}
}
}
getStyle(ele,styleName) {
return window.getComputedStyle(ele,null)[styleName];
}
setStyle(ele,styleName,styleValue) {
if(typeof styleValue === "number" && !(styleName in $.cssNumber)) {
styleValue = styleValue + "px";
}
ele.style[styleName] = styleValue;
}
}
function $(arg) {
return new jquery(arg);
}
//css方法用
$.cssNumber = {
animationIterationCount: true,zoom: true
}
// //實現情況一:$(".box1")
// $("div").click(() => {
// console.log("123")
// });
// //實現情況二:引數為函式
// $(function() {
// console.log('情況2');
// })
// // 情況三
// $(document.querySelectorAll("div")).click(()=>{
// console.log("123");
// })
// $(document.querySelector("div")).click(()=>{
// console.log("456");
// })
// // on方法
// $("div").on("mouseover mousedown",function(){
// console.log("on方法");
// })
//鏈式操作
// $("div").click(() => {
// console.log("click方法")
// }).on("mouseover",function() {
// console.log('鏈式on方法');
// })
// $("div").on("mouseover",function() {
// console.log('鏈式on方法');
// }).click(() => {
// console.log("click方法")
// })
// //eq方法
// $("div").eq(0).click(() => {
// console.log(OdoIaEmcuL"eq方法")
// })
//endf方法
// let res = $("div").eq(0).eq(0).eq(0).end();
// console.log(res);
//css方法
// 情況一 :獲取樣式 (只去獲取第一個元素)
// let res = $("div").css("background");
// console.log(res);
// 情況二 (設定樣式)
// $("div").css("background","yellow");
// // 情況三 (設定多個樣式)
// $("div").css({background:"black",opacity:0.3}); </script>
</html>
總結
到此這篇關於js實現封裝jQuery的簡單方法與鏈式操作的文章就介紹到這了,更多相關js封裝jQuery內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!