1.
function $(id) {
return typeof id === 'string'? document.getElementById(id) : null;
}
2.共享onload事件addLoadEvent
function addLoadEvent(func) {
var oldonload = window.onload;
if(typeof window.onload != 'function'){
window.onload = func;
}else {
window.onload = function () {
oldonload();
func();
}
}
}
3.insertAfter函数
function insertAfter(newElement,targetElement){
var parent = targetElement.parentNode;
if(parent.lastChild == targetElement){parent.appendChild(newElement);}
else{parent.insertBefore(newElement,targetElement.nextSibling);}
}
4.获得下一个元素节点(而不是下一个节点)getNextElement
function getNextElement(node) {
if(node.nodeType == 1){
return node;
}
if(node.nextSibling){
return getNextElement(node.nextSibling);
}
return null;
}
5.添加className属性并赋值/追加赋值addClass
function addClass(element,value) {
if(!element.className){element.className = value;}
else{
newClassName = element.className;
newClassName += ' ';
newClassName += value;
element.className = newClassName;
}
}
6.moveElement函数
function moveElement(elementID,final_x,final_y,interval) {
if(!document.getElementById){return false;}
if(!document.getElementById(elementID)){return false;}
var elem = document.getElementById(elementID);
var xpos = parseInt(elem.style.left);
var ypos = parseInt(elem.style.top);
if(xpos == final_x && ypos == final_y){return true;}
if(xpos < final_x){xpos++;}
if(xpos > final_x){xpos--;}
if(ypos < final_y){ypos++;}
if(ypos > final_y){ypos--;}
elem.style.left = xpos + 'px';
elem.style.top = ypos + 'px';
var repeat = 'moveElement'+'("'+elementID+'",'+final_x+','+final_y+','+interval+')';
movement = setTimeout(repeat,interval);
}
function moveElement(elementID,final_x,final_y,interval) {
if(!document.getElementById){return false;}
if(!document.getElementById(elementID)){return false;}
var elem = document.getElementById(elementID);
if(elem.movement){clearTimeout(elem.movement);}
//if(!elem.style.left || !elem.style.top){return false;}
if(!elem.style.left){elem.style.left = '0px';}
if(!elem.style.top){elem.style.top = '0px';}
var xpos = parseInt(elem.style.left);
var ypos = parseInt(elem.style.top);
if(xpos == final_x && ypos == final_y){return true;}
if(xpos < final_x){
dist = Math.ceil((final_x - xpos)/10);
xpos += dist;}
if(xpos > final_x){
dist = Math.ceil((xpos - final_x)/10);
xpos -= dist;}
if(ypos < final_y){
dist = Math.ceil((final_x - ypos)/10);
ypos += dist;}
if(ypos > final_y){
dist = Math.ceil((ypos - final_x)/10);
ypos -= dist;}
elem.style.left = xpos + 'px';
elem.style.top = ypos + 'px';
var repeat = 'moveElement'+'("'+elementID+'",'+final_x+','+final_y+','+interval+')';
elem.movement = setTimeout(repeat,interval);
}