ContentEditable focus in Chrome/Safari

后端 未结 2 2040
醉酒成梦
醉酒成梦 2021-01-12 14:25

I have a contenteditable div which needs to be focussed at pageload (place cursor at the first line).

document.getElementById(\"editor\").focus() works

相关标签:
2条回答
  • 2021-01-12 14:31

    I was able to add focus to a DIV by calling the focus() method chained to the attr() method

    $el.attr('contenteditable', "true").focus()
    
    0 讨论(0)
  • 2021-01-12 14:50

    This question may no longer be relevant to the questioner but I'll answer it for future readers. The basic principle is to set the selection to a collapsed range at the start of the element.

    I solved this problem by using the Rangy JS library: http://code.google.com/p/rangy

    var r = rangy.createRange();
    r.setStart( document.getElementById('editor'), 0 );
    r.collapse(true);
    rangy.getSelection().setSingleRange(r);
    

    This might be more than is necessary but it definitely works cross-browser and Rangy provides a bunch of extra utilities as well so it's probably worth looking into :)

    0 讨论(0)
提交回复
热议问题