zoukankan      html  css  js  c++  java
  • 老外可编辑div重新定位最后位置

    You can try this code, it can auto focus in your last insert location.

    let p = document.getElementById('contenteditablediv')
    let s = window.getSelection()
    let r = document.createRange()
    r.setStart(p, p.childElementCount)
    r.setEnd(p, p.childElementCount)
    s.removeAllRanges()
    s.addRange(r)


    To build further on @Surmon answer. If you are looking to auto focus right after your last letter/number in the text instead of the last insertion location (last insertion location will move the cursor to a new line if the child nodes are enclosed in block type tags and not plain text) then apply this small modification:

    r.setStart(p.lastChild, 1);
    r.setEnd(p.lastChild, 1);
    

    This is an extended function that checks if the editor/element has any child nodes and depending on the situation sets the cursor accordingly at the end:

    let p = document.getElementById('contenteditablediv');
    p.focus();  // alternatively use setTimeout(() => { p.focus(); }, 0);
    // this is enough to focus an empty element (at least in Chrome)
    
    if (p.hasChildNodes()) {  // if the element is not empty
      let s = window.getSelection();
      let r = document.createRange();
      let e = p.childElementCount > 0 ? p.lastChild : p;  
      r.setStart(e, 1); 
      r.setEnd(e, 1);    
      s.removeAllRanges();
      s.addRange(r);
    } 


    转载:https://stackoverflow.com/questions/2388164/set-focus-on-div-contenteditable-element
  • 相关阅读:
    bootstrap学习笔记
    java-多态
    java-重写
    java-继承
    java-包
    java-封装
    java-可变参数
    java-标准输入
    java-构造方法
    private、public、this关键字
  • 原文地址:https://www.cnblogs.com/BluceLee/p/12100044.html
Copyright © 2011-2022 走看看