js 选中div中的文本

 

function selectText(element) {
        var text = document.getElementById(element);
        if (document.body.createTextRange) {
            var range = document.body.createTextRange();
            range.moveToElementText(text);
            range.select();
        } else if (window.getSelection) {
            var selection = window.getSelection();
            var range = document.createRange();
            range.selectNodeContents(text);
            selection.removeAllRanges();
            selection.addRange(range);
            /*if(selection.setBaseAndExtent){
                selection.setBaseAndExtent(text, 0, text, 1);
            }*/
        } else {
            alert("none");
        }
    }

方法调用:

selectText('preBox');

 

posted on 2017-07-30 17:19  sjns  阅读(11912)  评论(0编辑  收藏  举报

导航