动态创建标记:
创建元素节点:
element = document.createElement(" ");
创建文本节点:
text = document.createTextNode(" ");
嵌入HTML文档内:
追加为一个节点的最后一个子节点:
element.appendChild(node);
在已有元素前插入新元素:
parentElement.insertBefore(newElement,targetElement);
//或者
targetElement.parentNode.insertBefore(newElement,targetElement);
在已有元素后插入新元素:
function insertAfter(newElement,targetElement) {
var parent = targetElement.parentNode;
if (parent.lastChild == targetElement) {
parent.appendChild(newElement);
} else {
parent.insertBefore(newElement,targetElement.nextSibling);
}
}
经过一定时间间隔排队执行某函数:
variable = setTimeout("function",interval);
//例如
movement = setTimeout("moveMessage()",5000);//5000毫秒
//有参数的情形
var repeat = "moveElement('" + elementId + "'," + finalX + "," + finalY + "," + interval + ")";
setTimeout(repeat,interval);
取消等待执行队列中的函数:
clearTimeout(variable);
应用:向某个位置移动元素
function moveElement(elementId,finalX,finalY,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.left = "0px";}
if (!elem.style.top) {elem.style.top = "0px";}
var xpos = parseInt(elem.style.left);//提取数字
var ypos = parseInt(elem.style.top);
if (xpos==finalX && ypos==finalY) {return true;}
//减速移动
xpos<finalX ? ( xpos += Math.ceil((finalX-xpos)/10) ) : ( xpos += Math.floor((finalX-xpos)/10) );
ypos<finalY ? ( ypos += Math.ceil((finalY-ypos)/10) ) : ( ypos += Math.floor((finalY-ypos)/10) );
/*
//平滑移动
xpos>finalX ? xpos-- : xpos;
xpos<finalX ? xpos++ : xpos;
ypos>finalY ? ypos-- : ypos;
ypos<finalY ? ypos++ : ypos;
*/
elem.style.left = xpos.toString() + "px";
elem.style.top = ypos.toString() + "px";
var repeat = "moveElement('" + elementId + "'," + finalX + "," + finalY + "," + interval + ")";
elem.movement = setTimeout(repeat,interval);
}