Javascript:双击时 window.getSelection 不正确

问题描述 投票:0回答:1

我希望当用户单击网页上的任何单词时打开字典。到目前为止它有效:

let str = window.getSelection().toString();
window.open("https://en.thefreedictionary.com/" + str, "_blank").focus();

但是现在,我希望用户可以选择多个单词,并且当他双击此选择时,词典或翻译工具应该自动打开。

在网页上,我有一句话“只要你需要,我就支持你”。如果我知道选择“只要”并双击它(在“长”一词上方),那么

window.getSelection.toString()
只会返回“长”而不是“只要”。那么为什么双击会删除选择呢?

我该如何解决这个问题?

javascript
1个回答
0
投票

要防止这种行为并打开词典或翻译工具进行全选,您可以:

  1. 在双击之前捕获选择。
  2. 如果选择包含以下内容,则防止默认的双击行为 多个单词。
  3. 使用全选触发词典/翻译工具。

代码:

// 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();
    }
});

说明:

  1. mousedown 事件:当用户点击时,我们捕获当前文本 选择。如果选择了多个单词,我们会阻止 双击使用 e.preventDefault() 重置选择。
  2. dblclick 事件:当用户双击时,我们检查当前 选择。如果选择了多个单词,我们打开字典 使用 window.open() 并将选定的文本作为 网址。

要点:

  1. 防止默认的双击行为:这会阻止浏览器 将选择重置为仅单击的单词。

  2. 处理多词选择:通过检查选择是否有 使用 split(/\s+/) 的多个单词,我们确保该工具打开 全选。

这样,您可以双击多词选择的任何部分,整个选择将传递到词典或翻译工具。

© www.soinside.com 2019 - 2024. All rights reserved.