同时也兼容HTML与XHTML
- <html>
- <head>
- <script>
- var _isDrag = false;
- var _dragObj;
- var _x,_y;
- var _scrollLeft,_scrollTop;
- function clickDIV(e){
- var _event = e || window.event;
- _dragObj = document.getElementById("dragDivId");
- _dragBg = document.getElementById("dragDivBg");
- _scrollLeft = document.compatMode == "CSS1Compat" ? document.documentElement.scrollLeft : document.body.scrollLeft;
- _scrollTop = document.compatMode == "CSS1Compat" ? document.documentElement.scrollTop : document.body.scrollTop;
- _x = _scrollLeft + _event.clientX;
- _y = _scrollTop + _event.clientY;
- _dragObj.style.fontSize = "0px";
- _dragObj.style.display = "block";
- _dragObj.style.left = _x + "px";
- _dragObj.style.top = _y + "px";
- _dragObj.style.borderColor = "#3399ff";
- _dragObj.style.borderWidth = "1px";
- _dragObj.style.borderStyle = "solid";
- _dragObj.style.width = "0px";
- _dragObj.style.height = "0px";
- _dragBg.style.backgroundColor = "#78b4f0";
- _dragBg.style.filter = "alpha(opacity=55)";
- _dragBg.style.opacity = "0.55";
- _dragBg.style.width = "0px";
- _dragBg.style.height = "0px";
- _isDrag = true;
- if(document.addEventListener){
- document.addEventListener("mousemove",dragDiv,false);
- document.addEventListener("mouseup",unclickDIV,false);
- }else{
- document.attachEvent("onmousemove",dragDiv);
- document.attachEvent("onmouseup",unclickDIV);
- _dragBg.setCapture();
- }
- }
- function dragDiv(e){
- if(_isDrag){
- var _event = e || window.event;
- var _divWidth = _scrollLeft + _event.clientX - _x;
- var _divHeight = _scrollTop + _event.clientY - _y;
- if(_divWidth < 0){
- _dragObj.style.left = _scrollLeft + _event.clientX + "px";
- }else{
- _dragObj.style.left = _x + "px";
- }
- if(_divHeight < 0){
- _dragObj.style.top = _scrollTop + _event.clientY + "px";
- }else{
- _dragObj.style.top = _y + "px";
- }
- _dragObj.style.width = Math.abs(_divWidth) + "px";
- _dragBg.style.width = Math.abs(_divWidth) + "px";
- _dragObj.style.height = Math.abs(_divHeight) + "px";
- _dragBg.style.height = Math.abs(_divHeight) + "px";
- }
- }
- function unclickDIV(e){
- _isDrag = false;
- _dragObj.style.display="none";
- if(document.removeEventListener){
- document.removeEventListener("mousemove",dragDiv,false);
- document.removeEventListener("mouseup",unclickDIV,false);
- }else{
- _dragBg.releaseCapture();
- }
- }
- window.onload = function(){
- var _divSelect = document.createElement("div");
- _divSelect.setAttribute("id","dragDivId");
- _divSelect.style.cssText="position:absolute;display:none;z-index:10";
- document.body.appendChild(_divSelect);
- var _divBg = document.createElement("div");
- _divBg.setAttribute("id","dragDivBg");
- _divSelect.appendChild(_divBg);
- document.body.onmousedown = clickDIV;
- }
- </script>
- </head>
- <body>
- </body>
- </html>