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

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

    Added jQuery.browser.webkit to the "else if" for Chrome. Could not get this working in Chrome 23.

    Made this script below for selecting the content in a

     tag that has the class="code".

    jQuery( document ).ready(function() {
        jQuery('pre.code').attr('title', 'Click to select all');
        jQuery( '#divFoo' ).click( function() {
            var refNode = jQuery( this )[0];
            if ( jQuery.browser.msie ) {
                var range = document.body.createTextRange();
                range.moveToElementText( refNode );
                range.select();
            } else if ( jQuery.browser.mozilla || jQuery.browser.opera  || jQuery.browser.webkit ) {
                var selection = refNode.ownerDocument.defaultView.getSelection();
                console.log(selection);
                var range = refNode.ownerDocument.createRange();
                range.selectNodeContents( refNode );
                selection.removeAllRanges();
                selection.addRange( range );
            } else if ( jQuery.browser.safari ) {
                var selection = refNode.ownerDocument.defaultView.getSelection();
                selection.setBaseAndExtent( refNode, 0, refNode, 1 );
            }
        } );
    } );
    

提交回复
热议问题