Use jQuery select() to select contents of a div

僤鯓⒐⒋嵵緔 提交于 2019-11-28 10:25:15
techfoobar

Check this fiddle: http://jsfiddle.net/JAq2e/

Basically the trick is to introduce a hidden text node whose content will be included in the selection when copied.

jQuery.fn.selectText = function(){
    this.find('input').each(function() {
        if($(this).prev().length == 0 || !$(this).prev().hasClass('p_copy')) { 
            $('<p class="p_copy" style="position: absolute; z-index: -1;"></p>').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);
    }
};

And use it like:

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

You can couple the above plugin with an event handler if you want to create selection links :

Code :

$('.select-text').on('click', function(e) {
    var selector = $(this).data('selector');
    $(selector).selectText();
    e.preventDefault();
});

Usage :

<a href="#" class="select-text" data-selector="#some-container">Select all</a>
<div id="some-container">some text</div>

Demo : see js fiddle

If you want to select the input elements together with every thing.

Here is a jQuery mixed, JS solution

function selectElement(element) {
    if (window.getSelection) {
        var sel = window.getSelection();
        sel.removeAllRanges();
        var range = document.createRange();
        range.selectNodeContents(element);
        sel.addRange(range);
    } else if (document.selection) {
        var textRange = document.body.createTextRange();
        textRange.moveToElementText(element);
        textRange.select();
    }
}

selectElement($("div")[0]); //Select the div
$("input").trigger("select");  //select the inputs

Demo

If you want to select inside form elements. Use .focus() /.blur() and .val() functions.

 $('input').focus(); //focus on input element
 $('input').val(); //return the value of input

Not really. In most browsers it's not possible for the contents of more than one input to be selected at once. See http://jsfiddle.net/timdown/D5sRE/1/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!