JavaScript 封装一些常用的函数
自己总结的一些常用的函数封装方法
1. addLoadEvent()
function addLoadEvent(func) {var oldonload = window.onload;if(typeof oldonload != "function"){window.onload = func;}else{window.onload = function() {oldonload();func();}}}
2. insertAfter()
function insertAfter(newElement,targetElement) {var parent = targetElement.parentNode;if(parent.lastChild == targetElement){parent.appendChild(newElement);} else{parent.insertBefore(newElement,targetElement.nextSibling);}}
3. getNextElement()
function getNextElement(node) {if(node.nodeType == 1) return node;if(node.nextSibling) return getNextElement(node.nextSibling);return null;}使用的时候 参数要设置为 所要获取的元素的nextSibling,例如getNrxtElement(element.nextSibling)
4. addClass()
function addClass(element,value) {if(!element.className) {element.className = value;} else {newClassName = element.className;newClassName += " ";newClassName += value;element.className = newClassName;}}
5. addEvent()
function addEvent(el, type, fn){if(el.addEventListener){el.addEventListener(type, fn, false);}else{el['e' + fn] = function(){fn.call(el, window.event);}el.attachEvent('on'+type, el['e'+fn]);}}
改进版(添加了返回值):
/**
* 跨浏览器事件处理工具。只支持冒泡。不支持捕获
* @author (qiu_deqing@126.com)
*/
var EventUtil = {
getEvent: function (event) {
return event || window.event;
},
getTarget: function (event) {
return event.target || event.srcElement;
},
// 返回注册成功的监听器,IE中需要使用返回值来移除监听器
on: function (elem, type, handler) {
if (elem.addEventListener) {
elem.addEventListener(type, handler, false);
return handler;
} else if (elem.attachEvent) {
var wrapper = function () {
event = window.event;
event.target = event.srcElement;
handler.call(elem, event);
};
elem.attachEvent('on' + type, wrapper);
return wrapper;
}
},
off: function (elem, type, handler) {
if (elem.removeEventListener) {
elem.removeEventListener(type, handler, false);
} else if (elem.detachEvent) {
elem.detachEvent('on' + type, handler);
}
},
preventDefault: function (event) {
if (event.preventDefault) {
event.preventDefault();
} else if ('returnValue' in event) {
event.returnValue = false;
}
},
stopPropagation: function (event) {
if (event.stopPropagation) {
event.stopPropagation();
} else if ('cancelBubble' in event) {
event.cancelBubble = true;
}
},
/**
* keypress事件跨浏览器获取输入字符
* 某些浏览器在一些特殊键上也触发keypress,此时返回null
**/
getChar: function (event) {
if (event.which == null) {
return String.fromCharCode(event.keyCode); // IE
}
else if (event.which != 0 && event.charCode != 0) {
return String.fromCharCode(event.which); // the rest
}
else {
return null; // special key
}
}
};
6. addClassName && removeClassName
function addClass(elem, cls) {
if (elem.className) { elem.className += ' ' + cls; } else { elem.className = cls; } }
function removeClass(elem, cls) { var className = ' ' + elem.className + ' '; var reg = new RegExp(' +' + cls + ' +', 'g'); elem.className = className.replace(reg, ' ').replace(/^ +| +$/, ''); }