跟随鼠标移动的盒子(包括检测边界值)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
div {
position: absolute;
top: 0px;
left: 0px;
width: 100px;
height: 100px;
background-color: red;
}
</style>
<body>
<div>111111111</div>
<script>
var div = document.getElementsByTagName('div')[0];
div.onmousedown = function(e) {
e = window.event || e;
// 鼠标按下 获取鼠标距离页面左侧距离
var x = e.clientX;
// 获取鼠标距离页面上侧距离
var y = e.clientY;
// 元素距离页面左侧距离
var elex = div.offsetLeft;
// 元素距离页面上侧距离
var eley = div.offsetTop;
// 相减得到鼠标距离元素的距离
var X = x - elex;
var Y = y - eley;
console.log(X, Y);
document.onmousemove = function(e) {
e = window.event || e;
// 鼠标移动过程中 获取鼠标距离页面距离
var movex = e.clientX;
var movey = e.clientY;
// 1.左侧边界值
// 元素移动过程中距离页面左侧距离
var leftx = movex - X;
var lefty = movey - Y;
// 1.左侧边界值
if (leftx <= 0) {
leftx = 0;
}
// 2.上侧边界值
if (lefty <= 0) {
lefty = 0
}
// 3.右侧边界值
// 页面可视区宽 -元素宽
var rightx = document.documentElement.clientWidth - div.offsetWidth;
if (leftx >= rightx) {
leftx = rightx
}
// 4.下侧边界值
// 页面可视区高 -元素高
var righty = document.documentElement.clientHeight - div.offsetHeight;
if (lefty >= righty) {
lefty = righty;
}
// 鼠标移动过程中 获取鼠标距离页面距离 - 鼠标距离元素的距离 =元素的left top值
div.style.left = leftx + 'px';
div.style.top = lefty + 'px';
}
// 抬起清除移动事件
document.onmouseup = function() {
document.onmousemove = null;
}
// 阻止默认事件
return false;
}
</script>
</body>
</html>