javascript 报错

来源:百度知道 编辑:UC知道 时间:2024/06/24 00:04:11
代码是:
<html>
<head>
<title>mini map</title>
<style type="text/css">
body{
padding : 0px ;
margin : 0px;
background-color : #999999 ;
}
.DivMain
{
position : absolute ;
text-align : center ;
overflow : hidden ;
width : 600px;
border :1px solid black;
}
.ImgMain {
position : absolute ;
overflow : hidden ;
border : 0px ;
}
</style>
<script language="javascript">
var ObjDrag;

function fnMouseDown() {
ObjDrag=document.getElementById("imgMain");
ObjDrag.setCapture();
l=event.x-ObjDrag.style.pixelLeft;
t=event.y-ObjDrag.style.pixelTop;
}
function fnMouseMove()
{

ObjDrag.style.left = event.x-l; 错误就说出在这行
ObjDrag.style.top = event.y-t;

}
function fnMouseUp() {
if(ObjDrag!=null) {

function fnMouseMove()
{
if(ObjDrag != null){
ObjDrag.style.left = event.x-l; //错误就说出在这行
ObjDrag.style.top = event.y-t;
}
}

增加if判断。
原因是触发fnMouseMove()之前,没有触发fnMouseDown(),即鼠标移动,但没有按下过,所以ObjDrag为null.
最佳的做法是定义一个Boolean标记,鼠标按下,标记为真,鼠标放开,标记为假。鼠标移动方法中,先判断标记是否为真(鼠标是否为按下状态,按下时才能移动目标)。

把第25行写成
var ObjDrag=document.getElementById("imgMain");
看看