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

后端 未结 16 1615
孤街浪徒
孤街浪徒 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:17

    Here's a version with no browser sniffing and no reliance on jQuery:

    function selectElementText(el, win) {
        win = win || window;
        var doc = win.document, sel, range;
        if (win.getSelection && doc.createRange) {
            sel = win.getSelection();
            range = doc.createRange();
            range.selectNodeContents(el);
            sel.removeAllRanges();
            sel.addRange(range);
        } else if (doc.body.createTextRange) {
            range = doc.body.createTextRange();
            range.moveToElementText(el);
            range.select();
        }
    }
    
    selectElementText(document.getElementById("someElement"));
    selectElementText(elementInIframe, iframe.contentWindow);
    

提交回复
热议问题