我正在创建一个富文本编辑器,我想使用相同的按钮来链接和取消链接选择。
document.execCommand('createLink'...)
和 document.execCommand('unlink'...)
允许用户链接和取消链接窗口.getSelection().toString()
.
但是,没有内置方法可以首先确定选择是否链接,所以我的问题是:如何检查选择是否链接?
我尝试使用 document.queryCommandState('createLink')
和 document.queryCommandState('unlink')
,但这两个查询始终返回 false
code>,即使 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 }
}
}
关于javascript - 检查选择是否包含链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47232304/