var drag = { enable : function(){ var domIdStr = arguments[0]; var parameter = {}; if(arguments.length == 2){ parameter = arguments[1]; } var dom = document.getElementById(domIdStr); dom.innerHTML = '<div id="' + domIdStr + 'dragHead"><span id="' + domIdStr + 'dragTitle"></span><a id="' + domIdStr + 'closeDrag">关闭</a></div>' + dom.innerHTML; var title = document.getElementById(domIdStr + 'dragTitle'); var close = document.getElementById(domIdStr + 'closeDrag'); var head = document.getElementById(domIdStr + 'dragHead'); var diffX = 0, diffY = 0, draging = false; dom.style.position = 'absolute'; dom.style.zIndex = parameter.zIndex || '1000'; dom.style.borderRadius = parameter.borderRadius || '4px'; dom.style.visibility = 'visible'; dom.style.width = parameter.width || '280px'; dom.style.height = parameter.height || '230px'; dom.style.backgroundColor = parameter.backgroundColor || '#F8F8F8'; var left, top, cWidth, cHeight, dWidth = dom.offsetWidth, dHeight = dom.offsetHeight; if(document.compatMode == "BackCompat"){ cWidth = document.body.clientWidth; cHeight = document.body.clientHeight; }else{ cWidth = document.documentElement.clientWidth; cHeight = document.documentElement.clientHeight; } left = cWidth/2 - dWidth/2; top = cHeight/2 - dHeight/2; dom.style.left = parameter.left || left + 'px'; dom.style.top = parameter.right || top + 'px'; dom.style.border = '1px solid #CCC'; head.style.cursor = 'move'; head.style.margin = '0'; head.style.backgroundColor = '#F2F2F2'; head.style.borderBottom = '1px solid #CCC'; head.style.padding = '5px'; title.innerHTML = dom.title; close.style.cursor = 'pointer'; close.style.cssFloat = 'right'; //Firefox close.style.styleFloat = 'right'; //IE head.onmousedown = function(e){ e = e || window.event; draging = true; diffX = e.clientX - dom.offsetLeft; diffY = e.clientY - dom.offsetTop; if(head.setCapture){ head.setCapture(); } head.onmousemove = function(e){ e = e || window.event; if(draging){ dom.style.left = (e.clientX - diffX) + 'px'; dom.style.top = (e.clientY - diffY) + 'px'; } }; head.onmouseup = function(e){ e = e || window.event; if(head.releaseCapture){ head.releaseCapture(); } draging = false; head.onmousemove = null; head.onmouseup = null; }; }; close.onclick = function(){ dom.style.visibility = 'hidden'; }; }, disable: function(domIdStr){ var dom = document.getElementById(domIdStr); dom.style.visibility = 'hidden'; } };
用法:在HTML页面添加
<div id="drag" title="温馨提示"><div>此JavaScript拖拽版本号已飚到3.0</div></div>