检查选择是否包含链接 [英] Check if selection contains link

查看:86
本文介绍了检查选择是否包含链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am creating a rich text editor and I would like to use the same button to link and unlink selections.

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

document.execCommand('createLink'...) and document.execCommand('unlink'...) allow users to link and 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?

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

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.

推荐答案

我找到了以下一段代码,它暂时运行得很好,在SO上踢:

I found the following piece of code, which works well enough for the time being, kicking around on 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 }
  }
}

这篇关于检查选择是否包含链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆