how to modify the document selection in javascript?

前端 未结 2 916
走了就别回头了
走了就别回头了 2020-12-03 18:56

I wanna modify the document selection (user currently selected by mouse or keyboard), how to do it in a cross browser way?

2条回答
  •  盖世英雄少女心
    2020-12-03 19:40

    As an example, and the easiest one, let's say you want to move the user's selection to contain the contents of an element. The following will work in all major browsers:

    function selectElementContents(el) {
        var body = document.body, range, sel;
        if (body.createTextRange) {
            range = body.createTextRange();
            range.moveToElementText(el);
            range.select();
        } else if (document.createRange && window.getSelection) {
            range = document.createRange();
            range.selectNodeContents(el);
            sel = window.getSelection();
            sel.removeAllRanges();
            sel.addRange(range);
        }
    }
    
    selectElementContents( document.getElementById("someElement") );
    

提交回复
热议问题