繁体   English   中英

检查选择是否包含链接

[英]Check if selection contains link

我正在创建一个富文本编辑器,我想使用相同的按钮来链接和取消链接选择。

document.execCommand('createLink'...)document.execCommand('unlink'...)允许用户链接和取消链接window.getSelection().toString()

但是,首先没有内置方法来确定选择是否链接,所以我的问题是:如何检查选择是否链接?

我曾尝试使用document.queryCommandState('createLink')document.queryCommandState('unlink') ,但两个查询总是返回false ,即使,例如, document.queryCommandState('bold')工作正常。

我发现了以下代码,它暂时运行良好,在 SO 上运行:

const isLink = () => {
  if (window.getSelection().toString !== '') {
    const selection = window.getSelection().getRangeAt(0)
    if (selection) {
      if (selection.startContainer.parentNode.tagName === 'A'
      || selection.endContainer.parentNode.tagName === 'A') {
        return [true, selection]
      } else { return false }
    } else { return false }
  }
}

您还可以检索链接 HTML 元素并将其传递给Selection.containsNode()

const linkHtmlElement = document.getElementById('yourId');
// should return true if your linkHtmlElement is selected
window.getSelection().containsNode(linkHtmlElement)

您需要检查anchorNodefocusNode文本节点以查看它们是否a元素。 有关MDN 的更多详细信息

 function isLink () { const selection = window.getSelection() const startA = selection.anchorNode.parentNode.tagName === 'A' const endA = selection.focusNode.parentNode.tagName === 'A' return startA || endA }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM