gpt4 book ai didi

javascript - 如何防止 Element.focus() 在 contenteditable div 中更改光标位置?

转载 作者:行者123 更新时间:2023-12-05 07:07:30 29 4
gpt4 key购买 nike

我不想将光标移动到任何地方,但当我调用函数 focus 时,它会将光标移动到开头。我希望将光标保持在原处。我正在使用 Typescript 在 ReactJS 中执行此操作。

const element = document.getElementById('editable-div');
element.focus(); // sets cursor to beginning here
// rest of my code is here

我想调用焦点,因为我需要在 contenteditable div 中追加内容,在某些情况下还需要插入内容。但是当我执行 focus() 时,它会将光标移动到错误的位置。我该如何解决这个问题?

最佳答案

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>

关于javascript - 如何防止 Element.focus() 在 contenteditable div 中更改光标位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62130358/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com