html
<!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>
<link rel="stylesheet" href="./css/index.css" />
</head>
<body>
<div class="note">
<div class="move-bar"></div>
<div class="content" contenteditable="">
<p>这是一个便笺</p>
<p>里面的文字可以更改</p>
<p>用鼠标按住顶部的移动条即可拖动便笺</p>
</div>
</div>
<script src="./js/index.js"></script>
</body>
</html>
css
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.note {
box-shadow: 0 0 5px #00000080;
width: 300px;
color: #333;
background: #fdf3a7;
position: fixed;
left: 100px;
top: 100px;
}
.move-bar {
background: #fbe961;
height: 10px;
cursor: move;
}
.content p {
margin: 1em 0;
padding: 0.5em;
}
.content {
outline: none;
}
js
// 让便签可被拖动,但不能超出视口
// 1. 获取元素
var moveBar = document.querySelector('.move-bar');
var note = document.querySelector('.note');
// 2. 注册鼠标按下事件
moveBar.onmousedown = function (e) {
// 2.1 获取鼠标按下的位置
var x = e.clientX;
var y = e.clientY;
// 2.2 获取元素的位置
var rect = note.getBoundingClientRect();
var ex = rect.left; // 元素的x坐标
var ey = rect.top; // 元素的y坐标
// 3. 注册鼠标移动事件
window.onmousemove = function (e) {
// 3.1 获取鼠标移动的距离
var distanceX = e.clientX - x; // 鼠标在x轴上移动的距离
var distanceY = e.clientY - y; // 鼠标在y轴上移动的距离
// 3.2 计算元素的新位置
var newLeft = ex + distanceX;
var newTop = ey + distanceY;
// 3.3 限制元素的新位置
if (newLeft < 0) {
newLeft = 0;
}
if (newTop < 0) {
newTop = 0;
}
if (newLeft > window.innerWidth - rect.width) {
newLeft = window.innerWidth - rect.width;
}
if (newTop > window.innerHeight - rect.height) {
newTop = window.innerHeight - rect.height;
}
// 3.4 设置元素的新位置
note.style.left = newLeft + 'px';
note.style.top = newTop + 'px';
}
// 4. 注册鼠标抬起事件
window.onmouseup = function () {
// 5. 注销鼠标移动事件
window.onmousemove = null;
// 6. 注销鼠标抬起事件
window.onmouseup = null;
}
}