以下为问题代码
window.onload = drag; function drag() { var box = getclassName("box")[0]; box.style.left = 500 + "px"; box.style.top = 200 + "px"; box.onmousedown = moveBox; //鼠标按下事件 } function moveBox(event) { var box = getclassName("box")[0]; var event = event || window.event; disX = event.clientX - box.style.left, //点击时的坐标差 disY = event.clientY - box.style.top; maxW = document.documentElement.clientWidth || document.body.clientWidth, //限制移动的最大宽度 maxY = document.documentElement.clientHeight || document.body.clientHeight; console.log("event.clientX: " + event.clientX); console.log("box.style.left: " + box.style.left); console.log("event.clientX + box.style.left: " + event.clientX + box.style.left); console.log("disX: " + disX); document.onmousemove = function(event) { var event = event || window.event; var posX = event.clientX - disX, //移动后BOX最终的坐标 posY = event.clientY - disY; if(posX < 0) { posX = 0; } else if(posX > maxW) { posX = maxW; } if(posY < 0) { posY = 0; } else if(posY > maxY) { posY = maxY; } box.style.left = posX + "px"; box.style.top = posY + "px"; document.onmouseup = function() { //释放鼠标 document.onmousemove = null; document.onmouseup = null; document.onmousedown = null; } } }在得出disX和disY计算值时因为event.clientX、box.style.left两者计算类型不行,导致结果为NaN类型。
解决办法是使用parseInt() 方法,把box.style.left转成数值类型。
if(isNaN(parseInt(box.style.left))) { disX = event.clientX - box.style.left; disY = event.clientY - box.style.top; } else { disX = event.clientX - parseInt(box.style.left); disY = event.clientY - parseInt(box.style.top); }