window.getSelection(): 返回一个Selection对象, 代表用户当前在文档中的选择。这个对象包含了用户选中的文本范围、起点、终点等信息。
.toString(): 调用Selection对象的toString()方法,该方法会返回用户当前选中的文本内容,以字符串的形式表现。
.getRangeAt(0) 用户进一步获取range对象获取到的 Range 对象可以用来进一步获取选中区域的起始和结束节点,以及相关的坐标信息,进而计算出选中区域的几何位置,以便在选中文字的正中间精确地放置提示框。
range.getBoundingClientRect() 计算选区的矩形位置
完整代码
<!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>
.aa {
width: 100px;
height: 40px;
background: red;
position: absolute;
}
</style>
</head>
<body>
<div id="div">这段代码会在用户鼠标抬起(mouseup)时检查是否有选中文本,如果有,则计算选区的位置,并在选区正中心创建并显示一个提示框。当鼠标离开页面或再次点击时,提示框会消失。
注意,实际使用时需要根据你的CSS样式和页面结构来调整提示框的位置计算方式,并且可能需要处理更多边缘情况。</div>
<div class="aa" id="aa">233</div>
<script>
document.getElementById("div").addEventListener(
"mouseup",
function handleMouseUp(e) {
console.log(1122)
// 获取选中的文本范围
var selection = window.getSelection();
if (selection.toString()) {
console.log(selection);
console.log(selection.toString())
// 如果有选中文本
var range = selection.getRangeAt(0);
console.log(range)
// 计算选区的矩形位置
var rect = range.getBoundingClientRect();
console.log(rect)
// 创建提示框元素
// var tooltip = document.createElement("div");
// tooltip.className = "tooltip";
// tooltip.textContent = "这是提示框内容";
// 设置提示框样式,使其居中显示在选区中央
document.getElementById('aa').style.position = "absolute";
document.getElementById('aa').style.left =
Math.round(rect.left + rect.width / 2 - document.getElementById('aa').offsetWidth / 2) +
"px";
document.getElementById('aa').style.top =
Math.round(
rect.top + rect.height / 2 - document.getElementById('aa').offsetHeight / 2
) + "px";
}
},
false
);
</script>
</body>
</html>