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

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

    You can use the following function to select content of any element:

    jQuery.fn.selectText = function(){
        this.find('input').each(function() {
            if($(this).prev().length == 0 || !$(this).prev().hasClass('p_copy')) { 
                $('

    ').insertBefore($(this)); } $(this).prev().html($(this).val()); }); var doc = document; var element = this[0]; console.log(this, element); if (doc.body.createTextRange) { var range = document.body.createTextRange(); range.moveToElementText(element); range.select(); } else if (window.getSelection) { var selection = window.getSelection(); var range = document.createRange(); range.selectNodeContents(element); selection.removeAllRanges(); selection.addRange(range); } };

    This function can be called as follows:

    $('#selectme').selectText();
    

提交回复
热议问题