/**
* fakeJquery 1.0.0
*
* 仿照Jquery简单设计,用于更方便的获取元素
*
* 开发时间 2020,11,27
*/
/**
* 传入样式,返回new的新原型对象内初始化函数
*/
var $ = function(style){
return new $.prototype.init(style);
}
/**
* 创建原型对象
*/
$.prototype = {
/**
* 存储元素DOM
*/
dom:Object,
/**
* 存储元素eq位置
*/
setIndex:function(x,y){
this.x = x;
this.y = y;
},
getIndex:function(n){
let arr = [this.x,this.y];
return arr[n];
},
/**
* 返回元素DOM
*/
init:function(style){
this.dom = document.querySelectorAll(style);
this.setIndex(0,this.dom.length)
return this;
},
/**
* css[object]:将同名css全部赋值样式
* css[string]:获取第一个css样式值
*/
css:function(s){
if(typeof(s) == "object"){
for(let i=this.getIndex(0);i<this.getIndex(1);i++){
for (let key in s) {
this.dom[i].style.setProperty(key,s[key]);
}
}
}else if(typeof(s) == "string"){
return getComputedStyle(this.dom[this.getIndex(0)]).getPropertyValue(s);
}
},
/**
* width:获取元素宽度(包括padding)
*/
width:function(){
return this.dom[this.getIndex(0)].clientWidth;
},
/**
* click:点击事件
*/
click:function(fun){
return this.dom[this.getIndex(0)].onclick = fun;
},
/**
* eq:获取第n个元素
*/
eq:function(n){
this.setIndex(n,n+1);
return this;
},
/**
* prepend:被选元素内部的开头添加内容
*/
prepend:function(str){
for(let i=0;i<this.getIndex(1);i++){
this.dom[i].insertAdjacentHTML('afterbegin', str);
}
},
/**
* append:被选元素内部的结尾添加内容
*/
append:function(str){
for(let i=0;i<this.getIndex(1);i++){
this.dom[i].insertAdjacentHTML('beforeend', str);
}
},
/**
* after:在被选元素之后插入内容
*/
after:function(str){
for(let i=0;i<this.getIndex(1);i++){
this.dom[i].insertAdjacentHTML('afterend', str);
}
},
/**
* before:在被选元素之前插入内容
*/
before:function(str){
for(let i=0;i<this.getIndex(1);i++){
this.dom[i].insertAdjacentHTML('beforebegin', str);
}
},
/**
* scrollTop:返回元素滚动条的垂直位置
*/
scrollTop:function(){
return this.dom[this.getIndex(0)].scrollTop;
},
/**
* scroll:用户滚动元素时触发
*/
scroll:function(fun){
return this.dom[this.getIndex(0)].onscroll = fun;
}
}
/**
* 创建原型链条
*/
$.prototype.init.prototype = $.prototype;
手写简单JQuery源码
最新推荐文章于 2024-05-04 18:53:16 发布