如何在没有execCommand的情况下切换选择文本的标签元素?

How to toggle tag element for selection text without execCommand?

提问人:Fitri Ahmed 提问时间:9/13/2023 最后编辑:Mr. PolywhirlFitri Ahmed 更新时间:9/13/2023 访问量:22

问:

所以,我正在为我的平台开发一个文本编辑器,我正在使用它,但它没有按预期工作,而且受到限制。所以我现在正在使用选择包围的内容等execCommand

问题是,我无法找出下一个函数来执行?

例如,让我们以粗体为例。当我选择文本并单击粗体按钮时,我希望将粗体应用于文本。

  1. 检查是否有元素作为父元素或父元素的父元素<strong>
  2. 如果 isset 和所选范围开始,只需删除元素并保留文本<strong>text</strong><strong>
  3. 如果 isset 和 selected 范围不是从头开始的,请将其转到<strong>te[x]t</strong><strong>te</strong>x<strong>t</strong>

所以我想让该函数适用于所有标签名称,并将其用于斜体、下划线等。我只想使用窗口选择。

到目前为止,我尝试过这个:

function toggleFormatting(tagName) {
  const selection = window.getSelection();
  if (!selection.isCollapsed) {
    const range = selection.getRangeAt(0);
    const selectedText = range.extractContents();

    // Check if the selected text is already wrapped in the specified tag
    const elements = selectedText.querySelectorAll(tagName);

    if (elements.length > 0) {
      // Case 1: If it's wrapped, unwrap it by replacing the tag with their contents
      elements.forEach((element) => {
        const parent = element.parentNode;
        while (element.firstChild) {
          parent.insertBefore(element.firstChild, element);
        }
        parent.removeChild(element);
      });
    } else {
      // Case 2: If it's not wrapped, wrap it with the specified tag
      const newElement = document.createElement(tagName);
      newElement.appendChild(selectedText);
      range.insertNode(newElement);
    }

    // Collapse the selection to remove any highlighting
    selection.removeAllRanges();
  }
}
JavaScript 文本选择

评论


答: 暂无答案