-
首先创建一个 div:
var div1 = document.createElement('div'); -
把该div插入到 body 元素的末尾处 :
document.body.appendChild(div1); -
定义一个拖曳标志 drapping:
var dragging = false; -
鼠标在div中按下时调用 div1.onmousedown 函数,改变拖曳状态:
div1.onmousedown = function (e) { dragging = true; lastX = e.clientX; lastY = e.clientY; } -
鼠标拖动时调用 document.onmousemove 函数,其中,外层是对是否对div进行拖曳的判断; 内层是对div是否会被拖出可视边界的判断:
document.onmousemove = function (e) { if (dragging === true) { var detalX = e.clientX - lastX; var detalY = e.clientY - lastY; var top = parseInt(div1.style.top) || 0; var left = parseInt(div1.style.left) || 0 var resultY = top + detalY; var resultX = left + detalX; var height = window.innerHeight - 100; var width = window.innerWidth - 100; if (resultX < 0 && resultY < 0) { div1.style.top = 0; div1.style.left = 0; } else if (resultX < 0 && resultY >= 0 && resultY <= height) { div1.style.top = resultY + 'px'; div1.style.left = 0; } else if (resultX < 0 && resultY > height) { div1.style.top = height + 'px'; div1.style.left = 0; } else if (resultX > 0 && resultX <= width && resultY < 0) { div1.style.top = 0; div1.style.left = resultX + 'px'; } else if (resultX > 0 && resultX <= width && resultY >= 0 && resultY <= height) { div1.style.top = resultY + 'px'; div1.style.left = resultX + 'px'; } else if (resultX > 0 && resultX <= width && resultY > height) { div1.style.top = height + 'px'; div1.style.left = resultX + 'px'; } else if (resultX > width && resultY < 0) { div1.style.top = 0; div1.style.left = width + 'px'; } else if (resultX > width && resultY >= 0 && resultY <= height) { div1.style.top = resultY + 'px'; div1.style.left = width + 'px'; } else if (resultX > width && resultY > height) { div1.style.top = height + 'px'; div1.style.left = width + 'px'; } lastX = e.clientX; lastY = e.clientY; } } -
松开鼠标,调用 document.onmouseup 函数,改变标志状态,拖曳结束:
document.onmouseup = function (e) { dragging = false; }