选区主要设计
- Selection 的 UI
- Selection 的 Rect(width,height) 变化
- Selection 的 Position 变化
- 在浏览器的 DOM 中,Selection 在鼠标点击位置的垂直线右侧变化于左侧变化的计算
Demo 演示
<!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>Document</title>
<style>
body {
background-color: #eee;
}
* {
margin: 0;
padding: 0;
box-sizing: content-box;
}
.main {
background-color: white;
box-shadow: 0 2px 4px 0px #333;
width: 960px;
height: 720px;
padding: 20px 40px;
}
.wrapper {
margin: 0 auto;
width: 960px;
height: 720px;
position: relative;
}
.selection {
border: 1px #33a3dc solid;
background-color: #33a3dc;
opacity: 0.3;
display: none;
position: fixed;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="main" id="main">
<div class="paragraph">你好啊</div>
</div>
<div class="selection" id="selection"></div>
</div>
<script>
let selectionShow = false;
let selectionRect = {
x: 0,
y: 0,
w: 0,
h: 0,
};
let mainEl = document.getElementById("main");
let eventContext = window;
function redrawSelection() {
let selectionEl = document.getElementById("selection");
if (!selectionShow) {
selectionEl.style.display = selectionShow
? "block"
: "none";
} else {
selectionEl.style.display = selectionShow
? "block"
: "none";
}
let mainElOffsetX = 0; //mainEl.getBoundingClientRect().x;
let mainElOffsetY = 0;
if (selectionRect.w < 0) {
selectionEl.style.left =
mainElOffsetX +
selectionRect.x +
selectionRect.w +
"px";
selectionEl.style.width = Math.abs(selectionRect.w) + "px";
} else {
selectionEl.style.left =
mainElOffsetX + selectionRect.x + "px";
selectionEl.style.width = selectionRect.w + "px";
}
if (selectionRect.h < 0) {
selectionEl.style.top =
mainElOffsetY +
selectionRect.y +
selectionRect.h +
"px";
selectionEl.style.height = Math.abs(selectionRect.h) + "px";
} else {
selectionEl.style.top =
mainElOffsetY + selectionRect.y + "px";
selectionEl.style.height = selectionRect.h + "px";
}
}
eventContext.addEventListener("mousedown", function (evt) {
selectionShow = true;
console.log("mousedown", evt);
selectionRect.x = evt.clientX;
selectionRect.y = evt.clientY;
redrawSelection();
});
eventContext.addEventListener("mousemove", function (evt) {
if (selectionShow) {
console.log("mousemove", evt);
selectionRect.w = evt.clientX - selectionRect.x;
selectionRect.h = evt.clientY - selectionRect.y;
redrawSelection();
}
});
eventContext.addEventListener("mouseup", function (evt) {
selectionShow = false;
redrawSelection();
});
</script>
</body>
</html>
体验地址
https://codesandbox.io/s/autumn-voice-4ghxn?file=/index.html