代码如下。代码本身是没问题的,可以运行。但是每次创建dragDiv对象时,就会要创建多个 像
drag.handMouseDown = function (e) 这样的function。书上说这样会占内存之类的。所以想请个位大哥大姐们请教下,如何改成每次new 一个dragDiv方法时候,不重新创建里面的方法。书上介绍的是用原型创建方法。我改过了,改到一半改不下去了希望大哥大姐帮帮忙,如果可以的话,最好帮我直接重新写下代码谢谢。
function dragDiv(cidv)
{
this.cidv = cidv;
} dragDiv.prototype.createDragDiv = function()
{
createDragDiv(this.cidv);
}
function divIsExist(cidv)
{
if(document.getElementById(cidv) == null)
{
return false;
}
return true;
}
function createDragDiv(cidv)
{
var drag = new Object;
var v_div ;
if(divIsExist(cidv) == false)
{

v_div = document.createElement("div");
v_div.setAttribute("id",cidv);
document.body.appendChild(v_div);
}else
{
v_div = document.getElementById(cidv);
//alert(v_div);
}

drag.cdiv  = cidv;
drag.diffX = 0;
drag.diffY = 0;
drag.handMouseDown = function (e)
{
 e = e || event;
// alert(e);
var v_div = document.getElementById(drag.cdiv);

//alert(drag.cdiv);

drag.diffX = e.clientX - v_div.offsetLeft;
drag.diffY = e.clientY - v_div.offsetTop;
if(document.addEventListener)
{
window.document.addEventListener("mousemove",drag.handMouseMove,false);
window.document.addEventListener("mouseup",drag.handMouseUp,false);

}else
{

window.document.attachEvent("onmousemove",drag.handMouseMove);
window.document.attachEvent("onmouseup",drag.handMouseUp);
}
}; drag.handMouseMove = function(e)
{
e = e|| event;
var v_div = document.getElementById(drag.cdiv);

v_div.style.top = (e.clientY - drag.diffY)+"px";
v_div.style.left = (e.clientX - drag.diffX)+"px";
}; drag.handMouseUp =  function()
{
if(window.document.removeEventListener)
{
window.document.removeEventListener("mousemove",drag.handMouseMove,false);
window.document.removeEventListener("mouseup",drag.handMouseUp,false);
}else
{

window.document.detachEvent("onmousemove",drag.handMouseMove);
window.document.detachEvent("onmouseup",drag.handMouseUp);
}
}; v_div.onmousedown = drag.handMouseDown;

return drag;
}//下面是使用该对象 <style type="text/css">
#divl
{

background-color:#C30;
top:100px;
left:200px;
width:100px;
height:100px;
position:absolute;

}
#div2
{

background-color:#C30;
top:400px;
left:400px;
width:100px;
height:100px;
position:absolute;

}
</style>
<script>
var drag4 = new dragDiv("divl");
drag4.createDragDiv();
var drag2 = new dragDiv("div2");
drag2.createDragDiv();
</script>