javascript元素拖拽效果的实现
主要涉及三个鼠标事件 mousedown,onmousemove和onmouseup
注意:onmouseup绑定在document对象上,因为释放鼠标时,有可能鼠标不在拖动的元素上
- 鼠标事件1 - 在标题栏上按下(要计算鼠标相对拖拽元素左上角的坐标,并且标记元素为可拖动)
- 鼠标事件2 - 鼠标移动时(要检测,元素是否可标记为移动,如果是,则更新元素的位置到当前鼠标的位置[要减去第一步中获得的偏移])
- 鼠标事件3 - 鼠标松开的时候(标记元素为不可拖动即可)
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>慕课网-拖拽实现</title>
<style type="text/css">
#draggable {
width: 100px;
height: 100px;
position: absolute;
top: 100px;
left: 100px;
border: 1px solid #ccc;
background: #eee;
padding: 10px;
cursor: default;
}
</style>
</head>
<body>
<div id="draggable">拖我</div>
<script type="text/javascript">
var oDrag = document.getElementById('draggable');
var isDraging = false;
var startX = 0;
var startY = 0;
oDrag.addEventListener('mousedown', function(e) {
//鼠标事件1 - 在标题栏按下(要计算鼠标相对拖拽元素的左上角的坐标 ,并且标记元素为可拖动)
var e = e || window.event;
mouseOffsetX = e.pageX - oDrag.offsetLeft;
mouseOffsetY = e.pageY - oDrag.offsetTop;
isDraging = true;
})
document.onmouseup = function(e) {
//鼠标事件3 - 鼠标松开的时候(标记元素为不可拖动)
isDraging = false;
}
document.onmousemove = function(e) {
//鼠标事件2 - 鼠标移动时(要检测,元素是否标记为移动)
var e = e || window.event;
var mouseX = e.pageX; //鼠标当前的位置
var mouseY = e.pageY;
var moveX = 0; //浮层元素的新位置
var moveY = 0;
if (isDraging === true) {
moveX = mouseX - mouseOffsetX;
moveY = mouseY - mouseOffsetY;
// 范围限定 moveX>0 并且 moveX < (页面最大宽度-浮层的宽度)
// moveY>0 并且 moveY < (页面最大高度-浮层的高度)
//页面宽高
var pageWidth = document.documentElement.clientWidth;
var pageHeight = document.documentElement.clientHeight;
//图层宽高
var dialogWidth = oDrag.offsetWidth;
var dialogHeight = oDrag.offsetHeight;
var maxX = pageWidth - dialogWidth;
var maxY = pageHeight - dialogHeight;
var moveX = Math.min(maxX, Math.max(0, moveX));
var moveY = Math.min(maxY, Math.max(0, moveY));
oDrag.style.left = moveX + 'px';
oDrag.style.top = moveY + 'px';
}
};
</script>
</body>
</html>