我正在使用Typescript和React创建富文本编辑器。 一切似乎都可以在Firefox上正常运行,但不能与Chrome一起运行。最重要的是,我发现的所有示例(在JS中)都可以在任一浏览器中正常运行。我不确定这是Typescript的错误还是我对DOM做错了。
此测试功能应创建一个span元素,并将其中所有字体的大小调整为25px。如果我突出显示了一些文本,它会起作用,但是如果我将插入号移动到行的末尾(或在中间并且不突出显示任何文本)并按tab,则插入号不会插入到跨度中,而是插入到跨度之前(在铬)。在Firefox中,插入符插入在标签之间,使我可以继续以25px的字体键入文字。
private readonly onKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {
//On tab key
if (event.keyCode === 9) {
const selection = window!.getSelection();
const contents = selection.toString();
//Create a span element with a font size of 25. Copy the highlighted contents.
let e = document.createElement('span');
e.style.fontSize = '25px';
e.innerHTML = contents;
//Replace the selection with the span element node.
let range = selection.getRangeAt(0);
range.deleteContents();
range.insertNode(e);
//Attempt to focus the caret between the newly created span?
//Works in firefox but not chrome??
selection.setPosition(e,0);
document.getElementsByTagName('span')[0].focus();
console.log(document.activeElement);
event.preventDefault();
}
}
它会这样使用,
<div
classname={'richtext-editor'}
contentEditable={true}
style={{ height: '350px' }}
ref={this.textEditorRef}
onKeyDown={this.onKeyDown}
onChange={(e) => {
this.setState({ content: e.currentTarget.nodeValue! });
}}
></div>