const insertNewLine = (e) => {
if (e.key === 'Enter') {
e.preventDefault();
// Create a new <p> element
const newParagraph = document.createElement('p');
newParagraph.innerHTML = '<br>'; // Add a line break to make the new paragraph visible
// Insert the new <p> element after the current selection
const selection = window.getSelection();
const range = selection.getRangeAt(0);
range.deleteContents();
range.insertNode(newParagraph);
// Move the caret inside the new <p> element
const newRange = document.createRange();
newRange.setStart(newParagraph, 0);
newRange.setEnd(newParagraph, 0);
selection.removeAllRanges();
selection.addRange(newRange);
}
};
2条答案
按热度按时间jc3wubiy1#
您可以处理
onKeyDown
事件来拦截Enter键并手动插入<p>
元素。字符串
vkc1a9a22#
字符串