简体   繁体   English

检查选择是否包含链接

[英]Check if selection contains link

I am creating a rich text editor and I would like to use the same button to link and unlink selections.我正在创建一个富文本编辑器,我想使用相同的按钮来链接和取消链接选择。

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

However, there are no inbuilt methods to determine whether a selection is linked or not in the first place, so my question is: How can you check whether or not a selection is linked?但是,首先没有内置方法来确定选择是否链接,所以我的问题是:如何检查选择是否链接?

I have tried using document.queryCommandState('createLink') and document.queryCommandState('unlink') , but both queries always return false , even though, for example, document.queryCommandState('bold') works properly.我曾尝试使用document.queryCommandState('createLink')document.queryCommandState('unlink') ,但两个查询总是返回false ,即使,例如, document.queryCommandState('bold')工作正常。

I found the following piece of code, which works well enough for the time being, kicking around on SO:我发现了以下代码,它暂时运行良好,在 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 }
  }
}

You also may be able to retrieve the link HTML element and pass it to Selection.containsNode()您还可以检索链接 HTML 元素并将其传递给Selection.containsNode()

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

You need to check the anchorNode and focusNode text nodes to see if they are a elements.您需要检查anchorNodefocusNode文本节点以查看它们是否a元素。 More details on MDN有关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