这是帮一个网友写的一个拖动层改变层尺寸DEMO 核心代码如下: var wrapId = " dragDiv " ; var wrap = getElementById(wrapId); var isChangeLayout; wrap.onmouseover = function () ... { isChangeLayout=getElementById('layout').checked?true:false; wrap.style.cursor = isChangeLayout?"move":"se-resize"; if (window.ActiveXObject) wrap.onselectstart = function () ...{ event.returnValue = false; } document.onmousedown = function (evt) ...{ /**//* save the original coordinates */ evt = window.event||evt; var a=getAbsoluteCoords(wrap); wrap.cx=evt.clientX-(isChangeLayout?a.left:a.width); wrap.cy=evt.clientY-(isChangeLayout?a.top:a.height); document.onmousemove = function (evt) ...{ /**//* change the coords when mouse is moveing */ evt = window.event||evt; try ...{ if (isChangeLayout) ...{ wrap.style.left = (evt.clientX-wrap.cx)+"px"; wrap.style.top = (evt.clientY-wrap.cy)+"px"; } else ...{ wrap.style.width = (evt.clientX-wrap.cx)+"px"; wrap.style.height = (evt.clientY-wrap.cy)+"px"; } } catch (ex) ...{}; }; document.onmouseup = function () ...{ /**//* drag end release the event */ document.onmousemove = null; document.onmouseup = null; wrap.style.cursor="default"; }; }; }
上面的代码兼容了改变尺寸和改变布局的代码,所以多出了很多判断的代码,如果不做判断,10的确是可以把拖动的代码写完的。去掉判断语句即可。如下:
var wrapId = " dragDiv " ; var wrap = getElementById(wrapId); wrap.onmouseover = function () ... { wrap.style.cursor = "se-resize"; document.onmousedown = function (evt) ...{ evt = window.event||evt; var a=getAbsoluteCoords(wrap); wrap.cx=evt.clientX-a.width; wrap.cy=evt.clientY-a.height document.onmousemove = function (evt) ...{ evt = window.event||evt; wrap.style.width = (evt.clientX-wrap.cx)+"px"; wrap.style.height = (evt.clientY-wrap.cy)+"px"; }; document.onmouseup = function () ...{ document.onmousemove = null; document.onmouseup = null; wrap.style.cursor="default"; }; }; }
demo:http://www.never-online.net/code/js/dragdemo/
转:http://www.never-online.net/blog/article.asp?id=148
