div拖动

html中元素的拖动的实现原理是,当鼠标拖动元素时,改变元素的绝对定位的左边left和顶部top的位置.下面以简单的div拖动为例:

一、首先对div dragDiv 的css设置成position:absolute绝对定位.

    只有当鼠标在目标div上按下时,鼠标拖动中div才改变位置。当鼠标松开时,鼠标移动,div位置不变。

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>DIV 拖动</title>
<style type="text/css">
*{margin:0; padding:0;}
#dragDiv{width:200px; height:200px; border-radius:5px; background-color:#903; position:absolute; top:10px; left:10px;}
</style>
</head>

<body>
<div id="dragDiv">拖动元素DIV内的内容</div>
<script type="text/javascript">

function getId(id){return document.getElementById(id)};//根据元素ID返回元素
function dragDiv(dragControl, dragContent){
var _x = 0, _y = 0, _drag = false, cw, ch, sw, sh;
var dragContent = typeof dragContent == "undefined" ? dragControl : dragContent; //如果不存在第二个参数就把拖动对象设置为第一个参数

getId(dragControl).onmousedown = function(e){
_drag = true;

e = window.event?window.event:e;
cw = document.documentElement.clientWidth;
ch = document.documentElement.clientHeight;
sw = parseInt(getId(dragContent).offsetWidth);
sh = parseInt(getId(dragContent).offsetHeight);

_x = e.clientX - getId(dragContent).offsetLeft; // 获取当前鼠标相对div原点的坐标
_y = e.clientY - getId(dragContent).offsetTop;


};

document.onmousemove = function(e){
if(_drag){
e = window.event?window.event:e;
window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty(); // 禁止拖放对象文本被选择的方法
document.body.setCapture && getId(dragContent).setCapture(); // IE下鼠标超出视口仍可被监听

var x = e.clientX - _x;
var y = e.clientY - _y;

x = x < 0 ? x = 0 : x < (cw-sw) ? x :(cw-sw); // 是否超出窗口的判断
y = y < 0 ? y = 0 : y < (ch-sh) ? y :(ch-sh);

getId(dragContent).style.left = x + "px";
getId(dragContent).style.top = y + "px";
};
};

document.onmouseup = function(){
_drag = false;
document.body.releaseCapture && getId(dragContent).releaseCapture();
};
}

dragDiv("dragDiv");
</script>
</body>
</html>

posted @ 2014-04-19 23:03  烈火如歌007  阅读(481)  评论(0编辑  收藏  举报