问题描述
我正在创建一个富文本编辑器,我想使用相同的按钮链接和取消链接选择。
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 }
}
}
这篇关于检查选择是否包含链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!