我遇到了以下代码的问题。我需要在div的任何地方抓住div并移动它。它适用于 我已将变量resultx和resulty设置为100和50,但这意味着div仅被其中心抓取。当我需要抓住其他任何地方并且我试图计算resultx并且结果在下面的方式它不起作用并且div仅被其边缘移动或根本没有移动。你能看一下我的计算错误吗?我试图找到问题很长一段时间,但最后我觉得它看起来是正确的。 THX
<!DOCTYPE html>
<html lang='cs'>
<head>
<title></title>
<meta charset='windows-1250'>
<meta name='description' content=''>
<meta name='keywords' content=''>
<meta name='author' content=''>
<meta name='robots' content='all'>
<!-- <meta http-equiv='X-UA-Compatible' content='IE=edge'> -->
<link href='/favicon.png' rel='shortcut icon' type='image/png'>
<style type="text/css">
body{margin:0;}
#desk {height:100%;width:100%;background-color:lightgreen;position:absolute;}
#flying {height:100px;width:200px;background-color:lightblue;position:absolute;top:100px; left:100px;}
#watchit {height:150px;width:200px;background-color:yellow;position:absolute;top:500px; left:800px;}
</style>
<script type="text/javascript">
var catched=false; //alert(catched);
var currtop;
var currleft;
var resultx;
var resulty;
function trim(str){
return str.replace("px","");
}
function moveit(ev){
oflying=document.getElementById("flying");
currtop=oflying.style.top;
currleft=oflying.style.left;
currtop=trim(currtop);
currleft=trim(currleft);
if(catched){
//vzdalenostx=100;
//vzdalenosty=50;
resultx = ev.clientX - currleft;
resulty = ev.clientY - currtop;
if(resultx<0){resultx=0;}
if(resulty<0){resulty=0;}
if(resultx>200){resultx=200;}
if(resulty>100){resulty=100;}
//oflying.style.left = (ev.clientX-100) +"px";
//oflying.style.top = (ev.clientY-50) +"px";
oflying.style.left = (ev.clientX-resultx) +"px";
oflying.style.top = (ev.clientY-resulty) +"px";
}
}
function showresult(ev){
document.getElementById('watchit').innerHTML=
'X:'+ev.clientX+'<br />'+
'Y:'+ev.clientY+'<br />'+
'catched:'+catched+
'<br />Currtop:'+currtop+
'<br />Currleft:'+currleft+
'<br />resultx:'+resultx+
'<br />resulty:'+resulty
;
}
</script>
</head>
<body onLoad="showresult(event)">
<div id="desk" onmousemove="moveit(event);showresult(event);"
onmouseup="catched=false;"
onmousedown="catched=false;">
</div>
<div id="flying" onmousedown="catched=true;showresult(event);"
onmouseup="catched=false;showresult(event);"
onmousemove="moveit(event);showresult(event);">
</div>
<div id="watchit">
</div>
</body>
</html>