- 被移动元素必须为绝对定位
position:absolute;
- Dom
<div class = "move-container" >
<div class = "move" style="position:absolute; width:100px; height:100px; background:gray">
</div>
</div>
- Javasrtipt
var moveElem = document.querySelector('.move'); //待拖拽元素
var dragging; //是否激活拖拽状态
var tLeft, tTop; //鼠标按下时相对于选中元素的位移
//监听鼠标按下事件
document.addEventListener('mousedown', function(e) {
if (e.target == moveElem) {
dragging = true; //激活拖拽状态
var moveElemRect = moveElem.getBoundingClientRect();
tLeft = e.clientX - moveElemRect.left; //鼠标按下时和选中元素的坐标偏移:x坐标
tTop = e.clientY - moveElemRect.top; //鼠标按下时和选中元素的坐标偏移:y坐标
}
});
//监听鼠标放开事件
document.addEventListener('mouseup', function(e) {
dragging = false;
});
//监听鼠标移动事件
document.addEventListener('mousemove', function(e) {
if (dragging) {
var moveX = e.clientX - tLeft,
moveY = e.clientY - tTop;
moveElem.style.left = moveX + 'px';
moveElem.style.top = moveY + 'px';
}
});
下面是一个封装好的函数
- 封装拖拽函数
var funDrag = function(element, callback) {
callback = callback || function() {};
var params = {
left: 0,
top: 0,
currentX: 0,
currentY: 0,
flag: false
};
//获取相关CSS属性
var getCss = function(o,key){
return o.currentStyle? o.currentStyle[key] : document.defaultView.getComputedStyle(o,false)[key];
};
//拖拽的实现
if(getCss(element, "left") !== "auto"){
params.left = getCss(element, "left");
}
if(getCss(element, "top") !== "auto"){
params.top = getCss(element, "top");
}
//o是移动对象
element.onmousedown = function(event){
params.flag = true;
event = event || window.event;
params.currentX = event.clientX;
params.currentY = event.clientY;
};
document.onmouseup = function(){
params.flag = false;
if(getCss(element, "left") !== "auto"){
params.left = getCss(element, "left");
}
if(getCss(element, "top") !== "auto"){
params.top = getCss(element, "top");
}
callback();
};
document.onmousemove = function(event){
event = event || window.event;
if(params.flag){
var nowX = event.clientX, nowY = event.clientY;
var disX = nowX - params.currentX, disY = nowY - params.currentY;
element.style.left = parseInt(params.left) + disX + "px";
element.style.top = parseInt(params.top) + disY + "px";
}
}
};