<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.box{
width:200px;
height:200px;
background: orange;
border:10px solid green;
cursor:pointer;
/*鼠标上面变小手*/
position:absolute;
}
</style>
</head>
<body>
<!-- 思路:
1:创建一个div,拖拽对象
2:div的css样式
3:鼠标按下事件:获取鼠标位置,鼠标在div上的位置,窗口的位置
4:鼠标移动事件:
5鼠标松开事件:获取此时鼠标的位置,定位此时盒子的位置。
-->
<h1>拖拽</h1>
<hr>
<div class="box" id="box"></div>
<script>
//获取box元素
var div = document.getElementById('box');
//给元素绑定 鼠标按键按下事件
div.onmousedown = function(env){
//改变背景色
div.style.backgroundColor = "#999";
//获取event对象
var e = env || window.event;
//求出 鼠标在 div上的位置
var left = e.clientX - div.offsetLeft;
var top = e.clientY - div.offsetTop;
//求窗口的宽高
var w = window.innerWidth;
var h = window.innerHeight;
//绑定鼠标 移动事件
document.onmousemove = function(en){
//获取event对象
var e = en || window.event;
//获取鼠标坐标
var x = e.clientX;
var y = e.clientY;
//设置 div 的位置
div.style.left = Math.min(Math.max(x - left, 0), w - 220) +'px';
div.style.top = Math.min(Math.max(y - top, 0), h - 220)+ 'px';
}
}
//鼠标按键抬起事件
div.onmouseup = function(){
div.style.backgroundColor = "orange";
//解除 onmousemove 事件绑定
document.onmousemove = function(){
}
}
</script>
</body>
</html>
网友评论