您的位置:首页 > Web前端 > JavaScript

JS——封装一个可以连缀的DOM库

2017-04-05 09:42 302 查看
function $(){
return new Base();    //每次要调用new一个新对象否则回造成叠加
}
function Base(){
this.elements=[];    //因为要返回new对象所以创建一个数组保存获取的DOM对象
this.getId=function(id){
this.elements.push(document.getElementById(id));
return this;
};
this.getTagName=function(tagName){
var tags = document.getElementsByTagName(tagName);
for(var i = 0;i < tags.length;i++){    //getElementsByTagName获取的是数组要所以要遍历元素
this.elements.push(tags[i]);
};
return this;
};

this.getClass=function(className,n){
if(arguments.length==1){   //判断参数,如果1个参数是要获取所有Class
var all = document.getElementsByTagName("*");
for(var i = 0;i<all.length;i++){
if (all[i].className==className){
this.elements.push(all[i]);
}
}
}else if(arguments.length==2){   //两个参数是想获取第n个class
this.elements.push(document.getElementsByClassName(className)
);
}
return this;
};
}
Base.prototype.addClass=function(className){     //添加class
for(var i = 0;i < this.elements.length;i++){
this.elements[i].className += " " + className;
}
return this;
}

Base.prototype.css=function (attr,value){
for(var i = 0;i < this.elements.length;i++){
if(arguments.length==1){   //1个参数是要的到属性值
if(typeof window.getComputedStyle != "undefined"){  //判断浏览器是否支持getComputedStyle
return window.getComputedStyle(this.elements[i],null).getPropertyValue(attr);
}else if(typeof this.element[i].currentStyle != "undefined"){ //判断是否支持currentStyle
return this.element[i].currentStyle.getAttribute(attr);
}
}
this.elements[i].style[attr]=value;     //如果不是1个参数设置属性并返回对象
};
return this;
}
Base.prototype.html=function (value){     //innerHTML方法
for(var i = 0;i < this.elements.length;i++){
if(arguments.length==0){  //如果没传参数表示要获取innerHTML
return this.elements[i].innerHTML;
}
this.elements[i].innerHTML=value;   //有参数是要设置innerHTML
};
return this;
}
Base.prototype.click=function(fn){  //添加click方法
for (var i = 0;i < this.elements.length;i++){
this.elements[i].onclick=fn
};
return this;
}

这样就封装好了 一个 DOM相关方法;

每次这样调用:

$().getClass("box",1).css("backgroundColor","#ccc").innerHTML("直接获取了class名为box的第2个元素对象并设置了background-color为#ccc并设置标签内容为这段文字")

直接获取了class名为box的第2个元素对象并设置了background-color为#ccc并设置标签内容为这段文字,这样将很多DOM方法封装后 十分简便
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐