<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>拖拽</title>
<style>
div{
100px;
height: 100px;
background-color: brown;
position: absolute;
}
#box1{
100px;
height: 100px;
position: absolute;
left: 200px;
background-color:skyblue;
}
img{
100px;
height: 100px;
position: absolute;
left: 400px;
}
</style>
<script>
window.onload = function () {
var box = document.querySelector("#box");
var box1 = document.querySelector("#box1");
var img = document.querySelector("#img");
drag(box);
drag(box1);
drag(img);
// 将拖拽功能封装成了一个函数
function drag(obj) {
obj.onmousedown = function (event) {
// 兼容IE8 调用IE特有的方法setCapture()
obj.setCapture && obj.setCapture();
event = event || window.event;
// 得到盒子和鼠标之间的相对位移
var ol = event.clientX - obj.offsetLeft;
var ot = event.clientY - obj.offsetTop;
document.onmousemove = function (event) {
event = event || window.event;
// 更改盒子的偏移量, 并减去盒子和鼠标的相对位移
obj.style.left = event.clientX - ol + "px";
obj.style.top = event.clientY - ot + "px";
// 兼容IE8 调用IE特有的方法releaseCapture()
obj.releaseCapture && obj.releaseCapture();
};
document.onmouseup = function () {
// 结束事件onmousemove onmouseup
document.onmousemove = null;
document.onmouseup = null;
};
return false;
};
}
};
</script>
</head>
<body>
<div id="box"></div>
<div id="box1"></div>
<img src="../../images/headPortrait.jpg" id="img">
</body>
</html>