content editable cursor position

前端 未结 2 1580
一生所求
一生所求 2021-01-06 20:01

I have a div thats content editable and I wish to click on the edit button and the cursor appears at the start of the div, at the minute it appears at the end.



        
相关标签:
2条回答
  • 2021-01-06 20:40

    Check: Set cursor position on contentEditable <div>

    In addition for IE's, check also document.selection.createRange.

    0 讨论(0)
  • 2021-01-06 20:45

    jsFiddle: http://jsfiddle.net/X6Ab8/

    Code:

    $(".edit").click(function(e) {
        e.preventDefault();
    
        var div = $(this).parent().children("div")[0];
        div.focus();
    
        if (window.getSelection && document.createRange) {
            // IE 9 and non-IE
            var sel = window.getSelection();
            var range = document.createRange();
            range.setStart(div, 0);
            range.collapse(true);
            sel.removeAllRanges();
            sel.addRange(range);
        } else if (document.body.createTextRange) {
            // IE < 9
            var textRange = document.body.createTextRange();
            textRange.moveToElementText(div);
            textRange.collapse(true);
            textRange.select();
        }
    });
    
    0 讨论(0)
提交回复
热议问题