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

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)[n]);			
		}		
		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].οnclick=fn
	};
	return this;
}

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

每次这样调用:

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

直接获取了class名为box的第2个元素对象并设置了background-color为#ccc并设置标签内容为这段文字,这样将很多DOM方法封装后 十分简便

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值