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

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

    An Updated version that works in chrome:

    function SelectText(element) {
        var doc = document;
        var text = doc.getElementById(element);    
        if (doc.body.createTextRange) { // ms
            var range = doc.body.createTextRange();
            range.moveToElementText(text);
            range.select();
        } else if (window.getSelection) {
            var selection = window.getSelection();
            var range = doc.createRange();
            range.selectNodeContents(text);
            selection.removeAllRanges();
            selection.addRange(range);
    
        }
    }
    
    $(function() {
        $('p').click(function() {
            SelectText("selectme");
    
        });
    });
    

    http://jsfiddle.net/KcX6A/326/

提交回复
热议问题