鼠标拖动div,从而设置div固定在浏览器的某个位置。
代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title></title>
<style>
.circle{
width: 100px;
height: 100px;
border-radius: 50%;
background-color: #999999;
position: absolute;
top: 10px;
left: 10px;
}
.circle:hover{
cursor: move;
}
</style>
</head>
<body>
<div id="circle" class="circle" onmousedown="fn()"></div>
<script>
// 点击窗口触发
function fn() {
var circle = document.getElementById("circle");
var event = event || window.event;
// 1.获取鼠标在窗口(当前div)中的位置
var offsetX = event.offsetX
var offsetY = event.offsetY
let x = offsetX
let y = offsetY
// console.log('鼠标在窗口的位置:', offsetX, offsetY)
// 移动触发
document.onmousemove = function() {
var event = event || window.event;
// 2.获取鼠标在浏览器中的位置
var clientX = event.clientX
var clientY = event.clientY
// console.log('鼠标在浏览器的位置:', clientX, clientY)
// 3.计算相对位置
move(circle, clientX - x, clientY - y)
}
// 鼠标弹起触发
document.onmouseup = function() {
document.onmousemove = null
document.onmouseup = null;
}
}
function move(circle, x, y) {
// 可视窗口的大小
var winWid = document.documentElement.clientWidth || document.body.clientWidth;
var winHei = document.documentElement.clientHeight || document.body.clientHeight;
// console.log('可视化窗口', winWid + " === " + winHei);
// 可视窗口的大小去减掉 所需移动的窗口的大小,就可以的出这个窗口所能达到的最边缘值
winWid = winWid - 10 - circle.offsetWidth
winHei = winHei - 10 - circle.offsetHeight
if (x <= 0) {
x = 10
}
if (y <= 0) {
y = 10
}
if (x > winWid) {
x = winWid
}
if (y > winHei) {
y = winHei
}
circle.style.top = y + 'px'
circle.style.left = x + "px"
}
</script>
</body>
</html>