拽案例,效果如下:
代码如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title></title>
<style>
.box {
width: 100px;
height: 100px;
background-color: red;
position: absolute;
left: 500px;
top: 200px;
cursor: pointer;
}
</style>
</head>
<script>
window.onload = function () {
//获取事件相关元素;
var box = document.getElementsByClassName("box")[0];
//给元素绑定onmousedown事件
box.onmousedown = function (event) {
//获取鼠标指针相对于盒子的距离;
var x = event.clientX - box.offsetLeft;
var y = event.clientY - box.offsetTop;
//给盒子绑定onmousemove事件;
document.onmousemove = function (event) {
//盒子的位置等于鼠标指针的位置减去鼠标指针相对于盒子的位置;
var xx = event.clientX - x;
var yy = event.clientY - y;
//将得到的xx和yy,两个距离加上px,赋值给box.style.left和box.style.top;
box.style.left = xx + "px";
box.style.top = yy + "px";
}
}
//鼠标松开后,box不能继续跟着鼠标指针移动,所以给box绑定onmouseup事件,
box.onmouseup = function () {
//并给整个文档绑定鼠标移动事件为无效;
document.onmousemove = null;
}
}
</script>
<body>
<div class="box"></div>
</body>
</html>