#div1 {
width: 100px;
height: 100px;
background: red;
position: absolute;
}
html
<div id="div1">
</div>
js
window.onload = function () {
var oDiv = document.getElementById('div1');
//pc端
oDiv.onmousedown = function (ev) {
var oEvent = ev || event; //需要获取和事件相关的信息时使用
var disX = oEvent.clientX - oDiv.offsetLeft;
var disY = oEvent.clientY - oDiv.offsetTop; document.onmousemove = function (ev) {
var oEvent = ev || event;
var l = oEvent.clientX - disX;
var t = oEvent.clientY - disY; if (l < 0) {
l = 0;
} else if (l > document.documentElement.clientWidth - oDiv.offsetWidth) {
l = document.documentElement.clientWidth - oDiv.offsetWidth;
} if (t < 0) {
t = 0;
} else if (t > document.documentElement.clientHeight - oDiv.offsetHeight) {
t = document.documentElement.clientHeight - oDiv.offsetHeight;
} oDiv.style.left = l + 'px';
oDiv.style.top = t + 'px';
}; document.onmouseup = function () {
document.onmousemove = null;
document.onmouseup = null;
};
};
//移动端
// 拖拽
// 获取节点
var block = document.getElementById("right");
var oW, oH;
// 绑定touchstart事件
oDiv.addEventListener("touchstart", function (e) {
var touches = e.touches[0];
oW = touches.clientX - oDiv.offsetLeft;
oH = touches.clientY - oDiv.offsetTop;
//阻止页面的滑动默认事件
document.addEventListener("touchmove", defaultEvent, false);
}, false);
oDiv.addEventListener("touchmove", function (e) {
var touches = e.touches[0];
var oLeft = touches.clientX - oW;
var oTop = touches.clientY - oH;
if (oLeft < 0) {
oLeft = 0;
} else if (oLeft > document.documentElement.clientWidth - oDiv.offsetWidth) {
oLeft = (document.documentElement.clientWidth - oDiv.offsetWidth);
}
oDiv.style.left = oLeft + "px";
oDiv.style.top = oTop + "px";
}, false);
oDiv.addEventListener("touchend", function () {
document.removeEventListener("touchmove", defaultEvent, false);
}, false); function defaultEvent(e) {
e.preventDefault();
};
};