拖拽方块
先写一个靠边停着的方块;
<div style="width:100px;height:100px;background-color:red;position: absolute;left:20px;top:20px;"></div>
按照拖拽的逻辑,实现需求:
var div = document.getElementsByTagName('div')[0];
var disX,
disY;
// 鼠标按下
div.onmousedown = function (e) {
e = e || window.event;
console.log(e);
disX = e.pageX - parseInt(div.style.left); // 求出当前鼠标相对于方块的横向距离
disY = e.pageY - parseInt(div.style.top); // 求出当前鼠标相对于方块的纵向距离
// 鼠标移动 鼠标移动频次太快超出 div 的响应时,鼠标会脱离,所以改用 document
document.onmousemove = function(e){
console.log(e.pageX + ' ' + e.pageY);
div.style.left = e.pageX - disX + 'px'; // 方块的X坐标等于鼠标的坐标减去鼠标相对于方块的距离;
div.style.top = e.pageY - disY + 'px'; // 方块的Y坐标等于鼠标的坐标减去鼠标相对于方块的距离;
}
// 鼠标抬起
document.onmouseup = function(){
document.onmousemove = null; // 抬起时清除移动事件
}
}
封装到 drag() 函数里:
var div = document.getElementsByTagName('div')[0];
function drag(elem) {
var disX,
disY;
// 鼠标按下
addEvent(elem, 'mousedown', function (e) {
var event = e || window.event;
disX = event.clientX - parseInt(getStyle(elem, 'left'));
disY = event.clientY - parseInt(getStyle(elem, 'top'));
addEvent(document, 'mousemove', mouseMove);
addEvent(document, 'mouseup', mouseUp);
stopBubble(event);
cancelHandler(event);
});
// 鼠标移动
function mouseMove(e) {
var event = e || window.event;
elem.style.left = event.clientX - disX + "px";
elem.style.top = event.clientY - disY + "px";
}
// 鼠标抬起
function mouseUp(e) {
var event = e || window.event;
removeEvent(document, 'mousemove', mouseMove);
removeEvent(document, 'mouseup', mouseUp);
}
// 获取对象的样式 div.style.left
function getStyle(el, css) {
return el.style[css];
};
// 封装添加事件绑定兼容函数
function addEvent(el, type, fn) {
if (el.addEventListener) {
el.addEventListener(type, fn, false);
} else if (el.attachEvent) {
el.attachEvent('on' + type, function () {
fn.call(el);
});
} else {
el['on' + type] = null;
}
}
// 封装解除事件绑定兼容函数
function removeEvent(el, type, fn) {
if (el.removeEventListener) {
el.removeEventListener(type, fn, false);
} else if (el.detachEvent) {
el.detachEvent("on" + type, fn);
} else {
el["on" + type] = null;
}
}
// 封装停止冒泡兼容函数
function stopBubble(e) {
if (e.stopPropagation) {
e.stopPropagation();
} else {
e.cancelBubble = true;
}
}
// 封装阻止默认事件兼容函数
function cancelHandler(e) {
if (e.preventDefault) {
e.preventDefault();
} else {
e.returnValue = false;
}
};
}
drag(div);