Selected text inside div

前端 未结 2 758
不思量自难忘°
不思量自难忘° 2021-01-14 18:42

I want this text inside

to be highlighten (selected for copy) when page loads.

This is sample text
2条回答
  •  北恋
    北恋 (楼主)
    2021-01-14 18:52

    The solution change based on the current browser, with older version of jQuery I use $.browser, but now is deleted; to check it's IE and use the correct code check if document.body.createTextRange exist like:

    $(document).ready(function () {
        selectText('sample_div');
    });
    
    function selectText(element) {
        var text = document.getElementById(element);
        if (document.body.createTextRange) {
            var range = document.body.createTextRange();
            range.moveToElementText(text);
            range.select();
        } else {
            var selection = window.getSelection();
            var range = document.createRange();
            range.selectNodeContents(text);
            selection.removeAllRanges();
            selection.addRange(range);
        } 
    }
    

    Demo: http://jsfiddle.net/IrvinDominin/bKPcX/

提交回复
热议问题