简体   繁体   English

Javascript:单击即可使用 window.getSelection()?

[英]Javascript: use window.getSelection() with single click?

In JavaScript, I don't know how to use window.getSelection() with a single click?在 JavaScript 中,我不知道如何通过单击使用window.getSelection()

var s = window.getSelection();
s = s.toString().trim();
alert(s);

HTML contains: HTML 包含:

<p>This text contains --this; and that-that.</p>

If single click on --this;如果单击--this; the expected output should be this .预期的输出应该是这个 Double click should do this well, but how to do this with just a single click?双击应该可以很好地做到这一点,但是如何通过单击来做到这一点?

Thank you very much to all, I come to this solution:非常感谢大家,我来到这个解决方案:

$('p').bind('click', function () {
    var sel_obj = window.getSelection(); //it will return an object
    sel_obj.modify("move","forward","character");
    sel_obj.modify("extend","backward","word");

    sel_obj.modify("move","backward","character");
    sel_obj.modify("extend","forward","word");

    var text = sel_obj.toString().trim();
    text = text.toLowerCase();
    alert (text);

References: https://developer.mozilla.org/en-US/docs/Web/API/Selection参考资料: https : //developer.mozilla.org/en-US/docs/Web/API/Selection

https://developer.mozilla.org/en-US/docs/Web/API/Selection/modify https://developer.mozilla.org/en-US/docs/Web/API/Selection/modify

Detect which word has been clicked on within a text 检测文本中哪个单词被点击

You need for your javascript code to be triggered by an onclick event.您需要通过 onclick 事件触发您的 javascript 代码。

So inside your p element, set onclick to the name of your js function:所以在你的 p 元素中,将 onclick 设置为你的 js 函数的名称:

<p onClick="myFunction()">Whatever text here</p>

Where that function is defined as该函数定义为

var myFunction = function(){
    var s = window.getSelection();
    s = s.toString().trim();
    alert(s);
}

Give your this an identifier, then bind a click function:给你的 this 一个标识符,然后绑定一个点击函数:

<p>This text contains <span id="this">--this;</span> and that-that.</p>

$( "#this" ).click(function() {
    var s = window.getSelection();
    s = s.toString().trim();
    alert(s);
});

https://api.jquery.com/click/ https://api.jquery.com/click/

For double click, use .dblclick对于双击,请使用.dblclick

$( "#this" ).dblclick(function() {
    var s = window.getSelection();
    s = s.toString().trim();
    alert(s);
});

https://api.jquery.com/dblclick/ https://api.jquery.com/dblclick/

When you single-click you create a zero-length selection range, so the toString() of the selection is naturally going to be an empty string.当您单击时,您会创建一个长度为零的选择范围,因此选择的toString()自然会是一个空字符串。

If you want to know the whole word that exists where the single click occurred, you're going to have to dig a bit further into what getSelection() returns: https://developer.mozilla.org/en-US/docs/Web/API/Selection如果您想知道单击发生处存在的整个单词,您将不得不深入了解getSelection()返回的内容: https : //developer.mozilla.org/en-US/docs/网页/API/选择

The Selection object will tell you the node in the DOM tree where that zero-length selection exists, and the offset into that node where you clicked. Selection对象将告诉您 DOM 树中该零长度选择所在的节点,以及您单击的该节点的偏移量。 You could easily get all of the text that belongs to the node -- but that's more text than you want.您可以轻松获取属于该节点的所有文本——但这比您想要的要多。

What you'd further have to do is look at the text at the selection offset, and scan backward and forward from that point to look for word boundaries.您还需要做的是查看选择偏移处的文本,然后从该点向前和向后扫描以查找单词边界。

Sorry I don't know of a less complicated approach than this -- as far as I know there's nothing that's going to give you the whole word at a single-click selection automatically.抱歉,我不知道比这更简单的方法——据我所知,没有什么可以通过单击选择自动为您提供完整的单词。

This is my implementation, demo here这是我的实现,演示在这里

document.addEventListener('mouseup', (e) => {
    const selection = window.getSelection();
    if (!selection.isCollapsed) {
        console.info("[skipping] Selection detected");
        return;
    }

    const word = getWordAt(selection.focusNode.textContent, selection.focusOffset);
    if (!word) {
        console.info("[skipping] Nothing selected");
        return;
    }

    const range = selection.getRangeAt(0);

    const elementOfSelectedWord = range.startContainer.splitText(range.startOffset - word.offset),
        elementAfterSelectedWord = elementOfSelectedWord.splitText(word.word.length);

    const decoratedElementOfSelectedWord = document.createElement('span');
    decoratedElementOfSelectedWord.appendChild(document.createTextNode(elementOfSelectedWord.textContent));
    elementOfSelectedWord.parentNode.insertBefore(decoratedElementOfSelectedWord, elementAfterSelectedWord);
    elementOfSelectedWord.parentNode.removeChild(elementOfSelectedWord);

    const clientRect = decoratedElementOfSelectedWord.getBoundingClientRect();

    if (!isMousePosCoveredInClientRect(e, clientRect)) {
        console.info("[skipping] Mouse pos is not covered in client rect");
        return;
    }

    drawRedRect(clientRect);

    console.log(`${word.word}`);
})


function getWordAt(content, offset) {
    const matchLeft = content.substr(0, offset).match(/(\w+)$/);
    const left = matchLeft ? matchLeft[1] : "";

    const matchRight = content.substr(offset).match(/^(\w+)/);
    const right = matchRight ? matchRight[1] : "";

    if (!left && !right) {
        return null;
    }

    return {word: left + right, offset: left.length};
}

function isMousePosCoveredInClientRect(event, clientRect) {
    return (
        event.clientY >= clientRect.y &&
        event.clientY <= clientRect.y + clientRect.height &&
        event.clientX >= clientRect.x &&
        event.clientX <= clientRect.x + clientRect.width
    );
}

function drawRedRect(clientRect) { // this is to simulate a popup
    const div = document.createElement('div');
    Object.assign(div.style, {
        display: "block",
        position: "absolute",
        left: (clientRect.left + window.scrollX) + "px",
        top: (clientRect.top + window.scrollY) + "px",
        width: clientRect.width + "px",
        height: clientRect.height + "px",
        border: "1px solid red"
    });

    document.body.appendChild(div);
    setTimeout(() => {
        document.body.removeChild(div);
    }, 1000)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM