我遇到的问题是,如果不允许动画完成,它会出现故障。除此之外,一切都按我的计划进行。此外,如果您发现任何可以对“物理”进行改进以使其看起来更自然或令人兴奋的地方,请随意将其扔进去!另外我是 javascript 新手,因此非常感谢格式化建议!
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Click Move</title>
<script type="text/javascript">
document.onmousedown = getCursorXY;
function getCursorXY(e) {
var cursorX = (window.Event) ? e.pageX : event.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft :document.body.scrollLeft);
var cursorY = (window.Event) ? e.pageY : event.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);
positionMessage(cursorX,cursorY);
}
function positionMessage(cursorX,cursorY){
if (!document.getElementById) return false;
if (!document.getElementById("message")) return false;
var elem = document.getElementById("message");
elem.style.position = "absolute";
moveElement("message",cursorX,cursorY,20);
}
function moveElement(elementID,cursorX,cursorY,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 == cursorX && ypos == cursorY) {
return true;
}
if (xpos < cursorX) {
var dist = Math.sqrt(cursorX - xpos);
xpos += dist;
}
if (xpos > cursorX) {
var dist = Math.sqrt((xpos - cursorX));
xpos -= dist;
}
if (ypos < cursorY) {
var dist = Math.sqrt((cursorY - ypos));
ypos += dist;
}
if (ypos > cursorY) {
var dist = Math.sqrt((ypos - cursorY));
ypos -= dist;
}
elem.style.left = xpos + "px";
elem.style.top = ypos + "px";
var repeat = "moveElement('"+elementID+"',"+cursorX+","+cursorY+","+interval+")";
movement = setTimeout(repeat,interval);
}
function updateSpan(element){
message = document.getElementById("message");
newMessage = document.getElementById(element.id);
message.innerHTML = newMessage.id;
}
</script>
<style type="text/css">
#message {
width: 90px;
height: 50px;
background:#999;
z-index: 20;
}
#blue_box {
position: absolute;
top: 100px;
left: 100px;
width: 60px;
height: 50px;
background:#03F;
}
#red_box {
position: absolute;
top: 200px;
left: 100px;
width: 60px;
height: 50px;
background:#F00
}
</style>
</head>
<body>
<div id="message" style="top:50px; left:100px;">WEEEEE!!!!!</div>
<div id="blue_box" onclick="updateSpan(this)">Blue_Box</div>
<div id="red_box" onclick="updateSpan(this)">Red_Box</div>
</body>
</html>