JavaScript 如何在选择文本时显示自定义菜单
在一些文本编辑器中,当您选择文本时,它会显示编辑文本的菜单,并提供如调整文本对齐、增加文本大小、改变颜色等功能。Microsoft Word就是最好的示例。在Microsoft Word中,当您选择任何文本时,它会显示自定义的水平菜单,以对文本执行一些操作。
本教程将使用JavaScript来创建一个在选择文本时显示自定义菜单的功能。
语法
用户可以按照以下语法来显示自定义菜单:
let coOrdinates = document.querySelector(".content").getBoundingClientRect();
let posX = clientX - Math.round(coOrdinates.left) + "px";
let posY = clientY - Math.round(coOrdinates.top) - 25 + "px";
在上述语法中,我们获取内容div的坐标。之后,我们找到自定义文本菜单的x和y位置。接下来,我们可以使用JavaScript更改自定义文本菜单的位置。
步骤
- 步骤1 - 在HTML中,创建一个div并添加文本。同样,创建一个自定义菜单并使用CSS进行样式定义。
-
步骤2 - 在JavaScript中,使用addEventListner()方法,并在“mousedown”事件发生时,获取点击位置的坐标,并将它们存储在“clientX”和“clientY”变量中。
-
步骤3 - 当文档上发生“mouseup”事件时,使用getSelection()方法获取所选的HTML。
-
步骤4 - 使用toString()方法将HTML转换为文本。
-
步骤5 - 检查文本。如果文本为空,则隐藏自定义菜单。
-
步骤6 - 如果用户选择了一些文本,则获取所选文本的坐标。
-
步骤7 - 定义“posX”变量,并存储自定义菜单的水平位置。同时,定义“posY”变量来存储自定义菜单的垂直位置。
-
步骤8 - 使用“posX”和“posY”变量的值,设置自定义菜单的左侧和顶部位置。
示例
在下面的示例中,我们创建了一个div元素,并添加了一些文本内容。同时,我们还创建了自定义菜单,并使用CSS进行了样式定义。在自定义菜单中,我们添加了复制和剪切文本功能。
在JavaScript中,我们实现了上述步骤,以便在用户选择一些文本时显示自定义菜单。在输出中,用户可以尝试选择文本,然后他们将在文本顶部看到一个自定义菜单。
<html>
<head>
<style>
.hoverMenu { display: none; position: absolute; background: #a4a4a4; border-radius: 6px; height: 30px; }
.hoverMenu span{ color: #000; cursor: pointer; margin: 8px;}
</style>
</head>
<body>
<div class = "content">
<h2>Showing custom menu on text selection</h2>
<p>Select some text to see custom menu</p>
<p>TutorialsPoint is an online platform that provides free tutorials and resources on various programming languages, software tools, and technologies. </p>
<div class = "hoverMenu"> <span> Copy </span> <span> Cut </span> </div>
</div>
<script>
var clientX, clientY;
document.addEventListener("mousedown", function (event) { clientX = event.pageX; clientY = event.pageY;});
document.addEventListener("mouseup", () => {
let selectionFromDocument = document.getSelection();
let textValue = selectionFromDocument.toString();
var hoverMenu = document.querySelector(".hoverMenu");
if (textValue == "") { hoverMenu.style.display = "none";
} else {
// get coOrdinates of the content div
let coOrdinates = document.querySelector(".content").getBoundingClientRect();
// set the display style of the hoverMenu to block
hoverMenu.style.display = "flex";
// set the position of the hoverMenu
let posX = clientX - Math.round(coOrdinates.left) + "px";
hoverMenu.style.left = posX;
posY = clientY - Math.round(coOrdinates.top) - 25 + "px";
hoverMenu.style.top = posY;
}
});
</script>
</body>
</html>
用户学会如何在文本选择时显示一些自定义的文本菜单。在这里,我们只添加了自定义文本菜单中的文本,但用户也可以根据需求添加功能。例如,当我们点击复制文本时,它应该将其复制到剪贴板中。
要显示文本选择的自定义菜单,需要获取所选文本的坐标,并相应地设置菜单的位置。