代码之家  ›  专栏  ›  技术社区  ›  Phillip Senn mpgn

setSelectionRange可用于输入字段,但如何将光标放在contenteditable字段的末尾?

  •  2
  • Phillip Senn mpgn  · 技术社区  · 7 年前

    我之前问过为什么setSelectionRange不工作,答案是因为它只处理输入字段。但我想尝试使用contenteditable属性开发一个电子表格类型的页面。

    window.onkeydown = function(e) {
    	if (e.keyCode === 113) {
        setFocus()
    	}
    }
    
    
    function setFocus() {
      element = document.getElementById('test')
      element.focus() // works
        .setSelectionRange(3,3) // Doesn't work
    }
    <div id="test" contenteditable>testing</div>
    <p>Click in the Result window and then press F2.</p>

    当用户按F2键时,如何将光标放在字段末尾?

    1 回复  |  直到 7 年前
        1
  •  1
  •   Badis Merabet    7 年前

    window.onkeydown = function(e) {
    	if (e.keyCode === 113) {
        setFocus()
    	}
    }
    
    
    function setFocus() {
      element = document.getElementById('test')
      element.focus() // works
      setCaretPosition(element,1); // Also works
    }
    
    function setCaretPosition(el, pos) {
       
      el.focus();
      var range = document.createRange();
      var sel = window.getSelection();
      range.setStart(el, pos);
      range.collapse(true);
      sel.removeAllRanges();
      sel.addRange(range);
    }
    <div id="test" contenteditable>testing</div>
    <p>Click in the Result window and then press F2.</p>