原生js实现jQuery常用方法的封装

/*jQuery封装*/
//$
window.$ = HTMLElement.prototype.$ = function(selector) {
	var elems = (this == window ? document : this).querySelectorAll(selector);
	return elems.length == 0 ? null : elems.length == 1 ? elems[0] : elems;
};
//css
HTMLElement.prototype.css = function(prop, value) {
	if(value === undefined) {
		if(typeof(prop) == 'object') {
			for(var key in prop) {
				this.style[key] = prop[key];
			}
			return this;
		} else {
			var style = getComputedStyle(this);
			return style[prop];
		}
	} else {
		this.style[prop] = value;
		return this;
	}
};
//attr
HTMLElement.prototype.attr = function(attr, value) {
	if(value === undefined) {
		this.getAttribute(attr);
		return this;
	} else {
		this.setAttribute(attr, value);
		return this;
	}
};
//class
HTMLElement.prototype.hasClass = function(cls) {
	return this.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
}

HTMLElement.prototype.addClass = function(cls) {
	if(!this.hasClass(cls)) this.className += " " + cls;
}

HTMLElement.prototype.removeClass = function(cls) {
	if(this.hasClass(cls)) {
		var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
		this.className = this.className.replace(reg, ' ');
	}
}
HTMLElement.prototype.toggleClass = function(cls) {
	if(this.hasClass(cls)) {
		this.removeClass(cls);
	} else {
		this.addClass(cls);
	}
}

猜你喜欢

转载自blog.csdn.net/zh_rey/article/details/78765828