Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
413 views
in Technique[技术] by (71.8m points)

javascript - 为什么我的光标不专注于聚焦元素?(Why does my curser not focus on the focused element?)

I have an editable main, in which when the user presses 'enter' a new paragraph element is appended to the child of this main element.

(我有一个可编辑的主体,其中,当用户按下“输入”时,新的段落元素将附加到该主体元素的子元素中。)

The new paragraph element is then focused.

(然后将重点放在新的段落元素上。)

However, the cursor doesn't automatically shift to the end of the text, it disappears.

(但是,光标不会自动移至文本的末尾,而是会消失。)

Why is this?

(为什么是这样?)

let m=document.getElementById('textEdit');
    function buttonClick(e){
  if (e.keyCode=="13"){
    e.preventDefault();
    let p=document.createElement("p");
    m.appendChild(p);
    p.tabIndex="-1";
    p.contentEditable='true';
    p.textContent="p";
    p.focus();
}
}
  ask by jamie translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Add this after p.focus :

(在p.focus之后添加:)

 document.execCommand('selectAll', false, null);
 document.getSelection().collapseToEnd();

See: https://codesandbox.io/s/wandering-glade-qsjlo

(参见: https : //codesandbox.io/s/wandering-glade-qsjlo)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...