javascript—在rangy包中的onkeypress事件时,关注插入的节点,而不是上一个元素

ffdz8vbo  于 2021-09-30  发布在  Java
关注(0)|答案(0)|浏览(263)

我需要将光标放置在新创建的段落的开头,同时在content-editable-div元素中触发key-down事件。我使用rangy库获取范围并将其插入到文档片段中。我需要专注于下一个开始元素。插入符号位置应放置在插入的节点上。但它放在一个包含div的break标记上。

  1. export const paraSplit = (Sel, Range) => {
  2. var clone_range = Range.cloneRange();
  3. var p = clone_range.commonAncestorContainer;
  4. while (p && p.nodeType !== 1) {
  5. p = p.parentNode;
  6. }
  7. if (p) {
  8. // Place the end of the range after the paragraph
  9. clone_range.setEndAfter(p);
  10. // Extract the contents of the paragraph after the caret into a fragment
  11. var contentAfterRangeStart = clone_range.extractContents();
  12. // Collapse the range immediately after the paragraph
  13. clone_range.collapseAfter(p);
  14. // Insert the content
  15. clone_range.insertNode(contentAfterRangeStart);
  16. // Move the caret to the insertion point
  17. clone_range.collapseAfter(p);
  18. Sel.setSingleRange(clone_range);
  19. Sel.setStart(Range.startContainer, Range.startOffset);
  20. return true;
  21. }
  22. };
  23. const ParaSplitHandler = (event) => {
  24. if (event.key === 'Enter') {
  25. rangy.init();
  26. //Initializing range selections
  27. let Sel = rangy.getSelection();
  28. let Range = Sel.getRangeAt(0);
  29. //ParaSplit function call on Enter event
  30. paraSplit(Sel, Range);
  31. }
  32. };
  33. <div
  34. id='main'
  35. onKeyPress={(event) => ParaSplitHandler(event)}
  36. ref={createId}
  37. >
  38. <div
  39. contentEditable='true'
  40. id='para1'
  41. className={styles.para}
  42. spellCheck='false'
  43. ref={focusNode}
  44. suppressContentEditableWarning={true}
  45. >
  46. As your React application scales and requirements change, you need a
  47. framework that you can depend on. Next.js allows you to seamlessly merge static sites, pre-rendered pages, and serverless functions. As your
  48. React application scales and requirements change, you need a framework that you can depend on. Next.js allows you to seamlessly merge static sites, pre-rendered pages, and serverless functions. As your React application scales and requirements change, you need a framework that you can depend on. Next.js allows you to seamlessly merge static sites,
  49. pre-rendered pages, and serverless functions.
  50. </div>
  51. </div>

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题