<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>CSS-DOM</title> <link rel="stylesheet" type="text/css" href="10.css" > <script src="10.js"></script> </head> <body> <p id="message"> Whee! </p> </body> </html>
function positionMessage(){ if(!document.getElementById) return false; if(!document.getElementById("message")) return false; var elem = document.getElementById("message"); elem.style.position = "absolute"; elem.style.left = "50px"; elem.style.top ="100px"; moveElement("message",200,100,10); } 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); //parseInt(string)把字符串里面的数值信息提取出来,因为后面要进行很多算术比较操作。 var ypos = parseInt(elem.style.top); //parseFloat(string)可以把带小数的数值(也就是浮点数)提取出来。 if(xpos == final_x && ypos == final_y){ return true; } if(xpos < final_x){ xpos++;} //如果xpos小于终点的left,给它加1. if(xpos > final_x){ xpos--;} //如果xpos大于终点的left,给它减1. if(ypos < final_y){ ypos++;} //如果ypos小于终点的left,给它加1. if(ypos > final_y){ ypos--;} //如果ypos大于终点的left,给它减1. elem.style.left = xpos + "px"; elem.style.top = ypos + "px"; //var repeat = function() {moveElement(elementID, final_x,final_y,interval)} var repeat = "moveElement(‘" + elementID + "‘," + final_x + "," + final_y + "," + interval + ")"; movement = setTimeout(repeat,interval); //clearTimeout(movement); 在等待的interval那时间内,可以取消这一“跳跃”行为 } addLoadEvent(positionMessage);
时间: 2024-12-27 22:53:09