首页 > 代码库 > 简单的鼠标拖拽
简单的鼠标拖拽
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<style type="text/css">
*{margin:0;padding:0;}
#box {
width: 100px;
height: 100px;
background: red;
position: absolute;
}
</style>
<script>
window.onload = function() {
var oDiv = document.getElementById("box");
var divX = 0;
var divY = 0;
oDiv.onmousedown = function(evt) {
var e = evt || window.event;
divX = e.offsetX;
divY = e.offsetY;
document.onmousemove = function(evt) {
var e = evt || window.event;
var x = e.clientX - divX;
var y = e.clientY - divY;
if (x < 0) {//左边界
x = 0;
}
if (y < 0) {//上边界
y = 0;
}
//window.innerWidth 指浏览器可视区宽度
if (x > window.innerWidth - oDiv.offsetWidth) {//右边界
x = window.innerWidth - oDiv.offsetWidth;
}
if (y > window.innerHeight - oDiv.offsetHeight) {//下边界
y = window.innerHeight - oDiv.offsetHeight;
}
oDiv.style.left = x + "px";
oDiv.style.top = y + "px";
}
document.onmouseup = function() {
document.onmousemove = null;
}
}
}
</script>
</head>
<body>
<div id="box"></div>
</body>
</html>
简单的鼠标拖拽