话不多说直接上代码
div class="calculator" id="drag"></div> //html代码
.calculator { //样式代码
position: absolute;
/*设置绝对定位,脱离文档流,便于拖拽*/
display: block;
width: 100px;
height: 100px;
background-color: #d6655c;
cursor: move;
/*鼠标呈拖拽状*/
}
var drag = document.getElementById('drag');
//点击某物体时,用drag对象即可,move和up是全局区域,也就是整个文档通用,应该使用document对象而不是drag对象
drag.onmousedown = function(e) {
var e = e || window.event;
var diffX = e.clientX - drag.offsetLeft;//鼠标按下那一刻相对于物体左侧边框的距离=点击时的位置相对于浏览器最左边的距离-物体左边框相对于浏览器最左边的距离
var diffY = e.clientY - drag.offsetTop;//同理计算距相对上边框位置
document.onmousemove = function(e) {
var e = e || window.event;
var left = e.clientX - diffX;//计算左边距
var top = e.clientY - diffY; //计算右边距
if (left < 0) { //过界判断
left = 0; //从左边移出浏览器窗口
} else if (left > window.innerWidth - drag.offsetWidth) {
left = window.innerWidth - drag.offsetWidth;//从右边移出浏览器窗口
}
if (top < 0) {
top = 0; //从上边移出浏览器窗口
} else if (top > window.innerHeight - drag.offsetHeight) {
top = window.innerHeight - drag.offsetHeight; //从下面移出浏览器窗口
}
drag.style.left = left + 'px';
drag.style.top = top + 'px';
}
document.onmouseup = function(e) { //移除事件,让物体停下
this.onmousemove = null;
this.onmouseup = null;
}
}