Selecting text in an element (akin to highlighting with your mouse)

后端 未结 16 1625
孤街浪徒
孤街浪徒 2020-11-21 05:58

I would like to have users click a link, then it selects the HTML text in another element (not an input).

By \"select\" I mean the same way you would select

16条回答
  •  别那么骄傲
    2020-11-21 06:12

    Plain Javascript

    function selectText(node) {
        node = document.getElementById(node);
    
        if (document.body.createTextRange) {
            const range = document.body.createTextRange();
            range.moveToElementText(node);
            range.select();
        } else if (window.getSelection) {
            const selection = window.getSelection();
            const range = document.createRange();
            range.selectNodeContents(node);
            selection.removeAllRanges();
            selection.addRange(range);
        } else {
            console.warn("Could not select text in node: Unsupported browser.");
        }
    }
    
    const clickable = document.querySelector('.click-me');
    clickable.addEventListener('click', () => selectText('target'));

    Some text goes here!

    Moar text!

    Click me!

    Here is a working demo. For those of you looking for a jQuery plugin, I made one of those too.


    jQuery (original answer)

    I have found a solution for this in this thread. I was able to modify the info given and mix it with a bit of jQuery to create a totally awesome function to select the text in any element, regardless of browser:

    function SelectText(element) {
        var text = document.getElementById(element);
        if ($.browser.msie) {
            var range = document.body.createTextRange();
            range.moveToElementText(text);
            range.select();
        } else if ($.browser.mozilla || $.browser.opera) {
            var selection = window.getSelection();
            var range = document.createRange();
            range.selectNodeContents(text);
            selection.removeAllRanges();
            selection.addRange(range);
        } else if ($.browser.safari) {
            var selection = window.getSelection();
            selection.setBaseAndExtent(text, 0, text, 1);
        }
    }
    

提交回复
热议问题