Created
February 21, 2018 19:06
-
-
Save duduindo/aa5f81ef8f6437de6c23ce120c0f8a58 to your computer and use it in GitHub Desktop.
Simple polyfill of Selection.prototype.containsNode
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import $ from 'jquery'; | |
/** | |
* {Element} Elemento que o browser tentará encontrar dentro da seleção | |
* | |
* @return bool | |
*/ | |
let containsNode = node => { | |
const selection = document.getSelection(); | |
// Mozilla, Chrome e Edge | |
return selection.containsNode(node, true); | |
}; | |
/** | |
* {Element} Elemento que o browser tentará encontrar dentro da seleção | |
* | |
* @about IE11 | |
* @return bool | |
*/ | |
const polyfill = node => { | |
const selection = document.getSelection(); | |
const start = selection.anchorNode.parentNode; | |
const final = selection.focusNode.parentNode; | |
const rectSelection = selection.getRangeAt(0).getBoundingClientRect(); | |
const rectBlock = node.getBoundingClientRect(); | |
// Verifica se o primeiro elemento selecionado está dentro do texto | |
if ($(start).closest(node).length) { | |
return true; | |
} | |
// Verifica se o último elemento selecionado está dentro do texto | |
if ($(final).closest(node).length) { | |
return true; | |
} | |
// Verifica se o selecionado é maior que o texto | |
if (rectSelection.top < rectBlock.top && rectSelection.height > rectBlock.height) { | |
return true; | |
} | |
return false; | |
}; | |
/** | |
* Se o navegador não der suporte ao Selection.containsNode, sobrescreve a função com polyfill | |
* MDN: https://goo.gl/oXfdVE | |
*/ | |
if (!('containsNode' in Selection.prototype)) { | |
containsNode = polyfill; | |
} | |
export { | |
containsNode, | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment