常用原生js函数封装

//封装ID
function $(id) {
	return typeof id === 'string' ? document.getElementById(id) : id;
}
//封装addClass,removeClass,toggleClass
function hasClass(obj, cls) {
	return obj.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
}

function addClass(obj, cls) {
	if (!this.hasClass(obj, cls)) obj.className += ' ' + cls;
}

function removeClass(obj, cls) {
	if (hasClass(obj, cls)) {
		var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
		obj.className = obj.className.replace(reg, ' ');
	}
}

function toggleClass(obj, cls) {
	if (hasClass(obj, cls)) {
		removeClass(obj, cls);
	} else {
		addClass(obj, cls);
	}
}
//封装tab切换
function tab(tit, con) {
	var titles = $(tit).getElementsByTagName('li'),
		contents = $(con).getElementsByTagName('li');
	for (var i = 0; i < titles.length; i++) {
		titles[i].id = i;
		titles[i].onmousedown = function() {
			for (var j = 0; j < titles.length; j++) {
				titles[j].className = '';
				contents[j].style.display = 'none';
			};
			this.className = 'on';
			contents[this.id].style.display = 'block';
		}
	}
}
//封装焦点轮播
function focus(wrap, pic, list, prev, next, isAuto) {
	var pic = $(pic),

		prev = $(prev),
		next = $(next),
		index = 0,
		timer = null,
		len = pic.getElementsByTagName('li').length,
		height = pic.getElementsByTagName('li')[0].offsetHeight;
	if (isAuto) {
		auto();
		if (wrap) {
			var wrap = $(wrap);
			wrap.onmouseover = clear;
			wrap.onmouseout = auto;
		}
		if (prev && next) {
			prev.onmouseover = clear;
			next.onmouseover = clear;
			prev.onmouseout = auto;
			next.onmouseout = auto;
		}
	}
	if (prev && next) {
		next.onclick = function() {
			index++;
			if (index >= len) {
				index = 0;
			}
			change(index);
		}
		prev.onclick = function() {
			index--;
			if (index < 0) {
				index = len - 1;
			}
			change(index);
		}
	}
	if (list) {
		var list = $(list).getElementsByTagName('li');
		for (var i = 0; i < len; i++) {
			list[i].title = i;
			list[i].onmouseover = function() {
				change(this.title);
			}
		}
	}
	function auto() {
		timer = setInterval(function() {
			index++;
			if (index >= len) {
				index = 0;
			}
			change(index);
		}, 2000);
	}
	function clear() {
		clearInterval(timer);
	}
	function change(curIndex) {
		pic.style.marginTop = -height * curIndex + 'px';
		if (list) {
			for (var n = 0; n < len; n++) {
				list[n].className = '';
			}
			list[curIndex].className = 'on';
		}
		index = curIndex;
	}
}
版权所有©转载必须以链接形式注明作者和原始出处

发表评论

电子邮件地址不会被公开。 必填项已用*标注