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

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

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

export const paraSplit = (Sel, Range) => {
    var clone_range = Range.cloneRange();

    var p = clone_range.commonAncestorContainer;

  while (p && p.nodeType !== 1) {
      p = p.parentNode;
   }

  if (p) {
// Place the end of the range after the paragraph
clone_range.setEndAfter(p);

// Extract the contents of the paragraph after the caret into a fragment
   var contentAfterRangeStart = clone_range.extractContents();

// Collapse the range immediately after the paragraph
  clone_range.collapseAfter(p);

// Insert the content
 clone_range.insertNode(contentAfterRangeStart);

// Move the caret to the insertion point
 clone_range.collapseAfter(p);

     Sel.setSingleRange(clone_range);
    Sel.setStart(Range.startContainer, Range.startOffset);

    return true;
 }
};

const ParaSplitHandler = (event) => {
    if (event.key === 'Enter') {
      rangy.init();
      //Initializing range selections
      let Sel = rangy.getSelection();
      let Range = Sel.getRangeAt(0);

      //ParaSplit function call on Enter event
      paraSplit(Sel, Range);

    }
  };

<div
      id='main'
      onKeyPress={(event) => ParaSplitHandler(event)}
      ref={createId}
    >
      <div
        contentEditable='true'
        id='para1'
        className={styles.para}
        spellCheck='false'
        ref={focusNode}
        suppressContentEditableWarning={true}
      >
        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, 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, 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,
        pre-rendered pages, and serverless functions.
      </div>
    </div>

暂无答案!

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

相关问题