![](/img/trans.png)
[英]element.focus() doesn't work on rerendered contentEditable div element
[英]How do I prevent Element.focus() change cursor position in contenteditable div?
我不想將 cursor 移動到任何地方,但當我調用 function 焦點時,它會將 cursor 移動到開頭。 我希望將 cursor 保留在原處。 我正在使用 Typescript 在 ReactJS 中執行此操作。
const element = document.getElementById('editable-div');
element.focus(); // sets cursor to beginning here
// rest of my code is here
我想調用焦點,因為我需要在 contenteditable div 中添加 append 內容,並且在某些情況下插入內容。 但是一旦我做focus()
,它就會將 cursor 移動到錯誤的位置。 我該如何解決?
在document.createRange和Window.getSelection的幫助下,這是可能的
const { useState, useEffect, useRef } = React; const random = (from, to) => Math.floor(Math.random() * (to - from) + from); const randomText = () => Array(random(5, 10)).fill(0).map((pr, index) => String.fromCharCode(index + 50)).join('') const setCaretToTheEnd = (element) => { const position = element.textContent.length; const [childNode] = element.childNodes; const range = document.createRange(); const selection = window.getSelection(); range.setStart(childNode, position); range.setEnd(childNode, position); range.collapse(true); selection.removeAllRanges(); selection.addRange(range); } const App = () => { const [text, setText] = useState(''); const inputRef = useRef(null); useEffect(() => { if(inputRef && inputRef.current && text) { const element = inputRef.current; setCaretToTheEnd(element); element.focus(); } }, [text]); useEffect(() => { let isUnmounted = false; let handle = null; const changeText = () => { setText(randomText()); handle = setTimeout(changeText, 4000); } handle = setTimeout(changeText, 500); return () => { isUnmounted = true; clearTimeout(handle); } }, []) const onChange = ({target: {value}}) => setText(value); return <div> <div ref={inputRef} suppressContentEditableWarning={true} className="contentEditable" onChange={onChange} contentEditable>{text}</div> </div> } ReactDOM.render( <App />, document.getElementById('root') );
.contentEditable { padding: 1rem; border: 1px solid black; }
<script src="https://unpkg.com/react/umd/react.development.js"></script> <script src="https://unpkg.com/react-dom/umd/react-dom.development.js"></script> <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script> <script src="https://unpkg.com/@material-ui/core@latest/umd/material-ui.development.js"></script> <div id="root"></div> <script src="https://unpkg.com/material-ui-lab-umd@4.0.0-alpha.32/material-ui-lab.development.js"></script> <div id="root"></div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.