Check if selection contains link

心不动则不痛 提交于 2019-12-24 18:59:32

问题


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().

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.


回答1:


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 }
  }
}


来源:https://stackoverflow.com/questions/47232304/check-if-selection-contains-link

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!