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

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

    Jason's code can not be used for elements inside an iframe (as the scope differs from window and document). I fixed that problem and I modified it in order to be used as any other jQuery plugin (chainable):

    Example 1: Selection of all text inside < code > tags with single click and add class "selected":

    $(function() {
        $("code").click(function() {
            $(this).selText().addClass("selected");
        });
    });
    

    Example 2: On button click, select an element inside an Iframe:

    $(function() {
        $("button").click(function() {
            $("iframe").contents().find("#selectme").selText();
        });
    });
    

    Note: remember that the iframe source should reside in the same domain to prevent security errors.

    jQuery Plugin:

    jQuery.fn.selText = function() {
        var obj = this[0];
        if ($.browser.msie) {
            var range = obj.offsetParent.createTextRange();
            range.moveToElementText(obj);
            range.select();
        } else if ($.browser.mozilla || $.browser.opera) {
            var selection = obj.ownerDocument.defaultView.getSelection();
            var range = obj.ownerDocument.createRange();
            range.selectNodeContents(obj);
            selection.removeAllRanges();
            selection.addRange(range);
        } else if ($.browser.safari) {
            var selection = obj.ownerDocument.defaultView.getSelection();
            selection.setBaseAndExtent(obj, 0, obj, 1);
        }
        return this;
    }
    

    I tested it in IE8, Firefox, Opera, Safari, Chrome (current versions). I'm not sure if it works in older IE versions (sincerely I don't care).

提交回复
热议问题