本文详细解析如何使用原生JavaScript模拟jQuery的核心功能,涵盖基础DOM选择、事件绑定、链式调用、元素筛选及样式操作。通过分步实现选择器、on方法、eq与end方法,展示如何构建类实例并返回this以支持链式操作,帮助开发者深入理解前端库的底层逻辑与面向对象封装技巧。
本文旨在梳理如何利用原生JavaScript封装jQuery的核心功能。
本文将通过JavaScript实现jQuery的部分方法,并拆解为8个具体目标逐步讲解。
- 实现$(".box1").click()方法
- 实现多元素点击事件绑定
- 分析选择器参数的三种处理情况
- 实现jQuery中的on事件方法
- 实现链式调用机制
- 实现jQuery中的eq元素筛选方法
- 实现jQuery中的end回溯方法
- 实现jQuery中的css样式操作方法
如有不当之处,欢迎在评论区指正,感谢支持。
1. 实现单个元素点击事件
首先设定第一个小目标,逐步实现下方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") 实现了DOM选择器的功能。
- $(".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")
});
至此,第一个小目标已完成,接下来继续第二个小目标。
2. 实现多个元素点击事件
第二个小目标涉及多个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. 分析选择器参数的三种情况
接下来第三个目标,考虑 $() 中参数的不同情况,列出以下三种(可能还有其他情况,此处暂不展开)。
情况一:$() 参数为字符串。
$(".box1")
情况二:$() 参数为函数。
//参数为函数
$(function() {
console.log("123");
})
情况三:$() 参数为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. 实现jQuery中的on方法
接下来实现第四个小目标,即模拟jQuery的on方法。
// 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);
}
}
}
测试运行结果是否通过。
// on方法
$("div").on("mouseover mousedown",function(){
console.log("on方法");
})
5. 实现链式调用
接下来实现第五个小目标,即实现jQuery的链式调用功能。
关键点在于在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. 实现jQuery中的eq方法
接下来实现第六个小目标,即实现jQuery中的eq方法。
//eq方法
eq(index) {
return new jquery(this[index]);
}
这里通过new一个jquery实例来实现,回顾一下new的过程:
- 执行构造函数
- 自动创建一个空对象
- 将空对象的原型指向构造函数的prototype属性
- 将空对象和函数内部的this绑定
- 如果return后跟随对象,则返回该对象;否则自动返回this对象
7. 实现jQuery中的end方法
实现第七个小目标,即实现jQuery中的end方法。要实现此功能,除新增end()方法外,还需在构造函数中增加参数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. 实现jQuery中的css方法
在jQuery中,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], j, args[0][j]);
}
}
}
}else {
//情况三
for(let i = 0; i < this.length; i++) {
this.setStyle(this[i], args[0], 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 arg.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;
// 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;
}
//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]);
}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]);
}
}
}
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,
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
}
// //实现情况一:$(".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("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",width:200,opacity:0.3}); </script>
</html>
总结
本文介绍了使用JS封装jQuery的简单方法及链式操作,更多相关js封装jQuery内容可搜索本站以前的文章或继续浏览下面的相关文章,希望大家以后多多支持本站!