一、目标效果
二、具体实现
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Text Selection Example</title>
<style>
#floating-panel {
display: none;
position: absolute;
background: white;
border: 1px solid #ccc;
padding: 10px;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
z-index: 1000;
}
#floating-panel button {
margin-right: 10px;
}
</style>
</head>
<body>
<div id="content">
<p>Select some text to see the floating panel. You can use this panel to copy or perform other actions.</p>
</div>
<div id="floating-panel">
<button id="copy-btn">Copy</button>
<button id="reply-btn">Reply</button>
</div>
<script>// script.js
document.addEventListener('DOMContentLoaded', function() {
var floatingPanel = document.getElementById('floating-panel');
var copyBtn = document.getElementById('copy-btn');
var replyBtn = document.getElementById('reply-btn');
function showPanel(x, y) {
floatingPanel.style.display = 'block';
floatingPanel.style.left = x + 'px';
floatingPanel.style.top = y + 'px';
}
function hidePanel() {
floatingPanel.style.display = 'none';
}
function copyText(text) {
var textArea = document.createElement('textarea');
textArea.value = text;
document.body.appendChild(textArea);
textArea.select();
document.execCommand('copy');
document.body.removeChild(textArea);
}
document.addEventListener('mouseup', function(event) {
var selection = document.getSelection();
if (selection.toString().length > 0) {
var range = selection.getRangeAt(0);
var rect = range.getBoundingClientRect();
showPanel(rect.left + window.scrollX, rect.top + window.scrollY + rect.height + 5);
} else {
hidePanel();
}
});
copyBtn.addEventListener('click', function() {
var selection = document.getSelection();
if (selection.toString().length > 0) {
copyText(selection.toString());
alert('Text copied to clipboard!');
hidePanel();
}
});
replyBtn.addEventListener('click', function() {
var selection = document.getSelection();
if (selection.toString().length > 0) {
var selectedText = selection.toString();
alert('Reply to: ' + selectedText);
hidePanel();
}
});
document.addEventListener('mousedown', function(event) {
// Hide panel if click outside of it
if (!floatingPanel.contains(event.target) && !event.target.matches('#copy-btn') && !event.target.matches('#reply-btn')) {
hidePanel();
}
});
});
</script>
</body>
</html>
这个示例演示了如何实现一个文本选择后出现的悬浮面板。该面板可以包含复制和其他操作按钮,提供了用户选择文本时的交互功能。你可以根据实际需要扩展和定制这个示例。
三、解释
-
HTML 和 CSS:
- 定义了一个
#floating-panel
元素作为悬浮面板,并设置了样式以确保其在页面上正确显示。 - 定义了两个按钮:
Copy
和Reply
,用来执行相应的操作。
- 定义了一个
-
JavaScript:
- 显示面板:
showPanel
函数根据传入的坐标设置悬浮面板的位置,并将其显示出来。 - 隐藏面板:
hidePanel
函数将悬浮面板隐藏。 - 复制文本:
copyText
函数使用document.execCommand('copy')
复制文本到剪贴板。 - 处理鼠标事件:
mouseup
事件用于检测用户是否选中了文本,并根据选中的文本显示悬浮面板。mousedown
事件用于隐藏面板(如果点击在面板之外)。
- 按钮点击事件:
copyBtn
按钮用于复制选中的文本。replyBtn
按钮用于处理回复操作(这里只是简单地弹出选中文本的提示)。
- 显示面板: