我希望当用户单击网页上的任何单词时打开字典。到目前为止它有效:
let str = window.getSelection().toString();
window.open("https://en.thefreedictionary.com/" + str, "_blank").focus();
但是现在,我希望用户可以选择多个单词,并且当他双击此选择时,词典或翻译工具应该自动打开。
在网页上,我有一句话“只要你需要,我就支持你”。如果我知道选择“只要”并双击它(在“长”一词上方),那么
window.getSelection.toString()
只会返回“长”而不是“只要”。那么为什么双击会删除选择呢?
我该如何解决这个问题?
要防止这种行为并打开词典或翻译工具进行全选,您可以:
代码:
// Listen for mousedown events to capture the selection
document.addEventListener('mousedown', function (e) {
if (window.getSelection) {
let selection = window.getSelection().toString();
// Prevent the default action if more than one word is selected
if (selection.trim().split(/\s+/).length > 1) {
e.preventDefault();
}
}
});
// Listen for double-click events to open the dictionary
document.addEventListener('dblclick', function (e) {
let selection = window.getSelection().toString();
// If multiple words are selected, open the dictionary
if (selection.trim().split(/\s+/).length > 1) {
window.open("https://en.thefreedictionary.com/" + encodeURIComponent(selection), "_blank").focus();
}
});
说明:
要点:
防止默认的双击行为:这会阻止浏览器 将选择重置为仅单击的单词。
处理多词选择:通过检查选择是否有 使用 split(/\s+/) 的多个单词,我们确保该工具打开 全选。
这样,您可以双击多词选择的任何部分,整个选择将传递到词典或翻译工具。