JS常用方法(获取Class、获取元素样式、事件监听、cookie、ajax等)

时间:2022-10-07 15:29:41
var Util = {};
Util.byClass = function (oClass) {//全局获取
	var tags = document.all ? document.all : document.getElementsByTagName('*');
	var arr = [];
	var reg = new RegExp("\\b" + oClass + "\\b");
	for (var i = 0; i < tags.length; i++) {
		if (reg.test(tags[i].className)) {
			arr.push(tags[i]);
		}
	}
	return arr;
};
Util.byClass2 = function (parentID, oClass) {//局部获取
	var parent = document.getElementById(parentID);
	var tags = parent.all ? parent.all : parent.getElementsByTagName('*');
	var arr = [];
	var reg = new RegExp("\\b" + oClass + "\\b");
	for (var i = 0; i < tags.length; i++) {
		if (reg.test(tags[i].className)) {
			arr.push(tags[i]);
		}
	}
	return arr;
};
Util.getStyle = function (obj, oStyle) {//获取元素的样式
	if (obj.currentStyle) {
		return obj.currentStyle[oStyle];
	} else {
		return getComputedStyle(obj, null)[oStyle];
	}
};
Util.addEvent = function (obj, type , fn) {//添加事件监听
	if (obj.addEventListener) {
		obj.addEventListener(type, fn, false);
	} else if (obj.attachEvent) {
		obj.attachEvent('on' + type, fn);
	} else {
		obj['on' + type] = fn;
	}
};
Util.removeEvent = function (obj, type, fn) {//删除事件监听
	if (obj.removeEventListener) {
		obj.removeEventListener(type, fn, false);
	} else if (obj.detachEvent) {
		obj.detachEvent('on' + type, fn);
	} else {
		obj['on' + type] = null;
	}
};
Util.getOffsetTL = function (obj) {//获取obj到body左右的offset值
	var l = 0, 
		t = 0;
	while (obj) {
		l = l + obj.offsetLeft + obj.clientLeft;
		t = t + obj.offsetTop + obj.clientTop;
		obj = obj.offsetParent;
	}
	return {left: l, top, t};
}
Util.setCookie = function (key, val, days) {
	var dates = new Date();
	dates.setDate(dates.getDate() + days);
	document.cookie = key + '=' + escape(val) + '; expires=' + dates;
};
Util.getCookie = function (key) {
	var arr1 = document.cookie.split('; ');
	for (var i = 0; i < arr1.length; i++) {
			var arr2 = arr1[i].split('=');
			if (arr2[0] == key) {
				return unescape(arr2[1]);
			} 
		}	
	return false;
};
Util.removeCooie = function (key) {
	Util.setCookie(key, 'aaa', -1);
};
Util.ajax = function (url, successFn, failureFn) {
	var xhr = null;
	if (window.XMLHttpRequest) {
		xhr = new XMLHttpRequest();
	} else {
		xhr = new ActiveXObject('Microsoft.XMLHTTP');
	}
	xhr.open('get', url, true);
	xhr.send(null);
	xhr.onreadystatechange = function () {
		if (xhr.readyState == 4) {
			if (xhr.status == 400) {
				successFn(xhr.responsText);
			} else {
				if (failureFn) {
					failureFn();
				} else {
					alert(xhr.status);
				}
			}
		} 
	}
}