先看效果
简单的布局
下面是JS代码
<script>
var box = document.getElementById("box");// 获取ID
limitDrag(box);
// 拖拽封装函数
function limitDrag(node) {
// 按下
node.onmousedown = function (e) {
var e = e || window.e;
// 鼠标离盒子边框的距离 当前鼠标离浏览器左上角的距离 - 当前盒子里浏览器左上角的距离
var offsetL = e.clientX - node.offsetLeft;
var offsetT = e.clientY - node.offsetTop;
// 点击之后获取当前窗口的宽高
var windowWidth = document.documentElement.clientWidth || document.body.clientWidth;
var windowHeight = document.documentElement.clientHeight || ocument.body.clientHeight;
// 移动
this.onmousemove = function (e) {
// 当前鼠标的距离 - 鼠标按下计算出来的距离
this.style.left = e.clientX - offsetL + "px";
this.style.top = e.clientY - offsetT + "px";
// 当鼠标移出到浏览器外面的时候停止 e.clientY+20 是可能有边框滚动条距离比window.innerHeight小触发不了if
if (e.clientY + 20 >= windowHeight || e.clientX + 20 >= windowWidth || e.clientY <= 0 || e
.clientX <= 0) {
this.onmousemove = null;
}
}
}
// 鼠标抬起时让移动等于空
node.onmouseup = function (e) {
this.onmousemove = null;
var target = e.target || window.event.srcElement;
}
}
</script>