Tengo una función Javascript para una extensión de Chrome que estoy creando y que muestra un diccionario emergente. Esto se hace insertando un nodo de intervalo debajo del texto que el usuario ha resaltado con el mouse.
function insertPopupDict() { if (window.getSelection) { var selection = window.getSelection(); var text = selection.toString(); var range = selection.getRangeAt(0); var popupDictionaryWindow = document.createElement('span'); popupDictionaryWindow.id = 'hawaiian-popup-dictionary' popupDictionaryWindow.style = 'margin-top: 35px; width: 360px;background-color: #555;color: #fff;text-align: center;border-radius: 6px;padding: 8px 0;position: absolute;z-index: 1;'; searchWord(text).then(defenitions => { popupDictionaryWindow.innerHTML = text + "<hr><br>"; for (var i = 0; i < defenitions.length; i++) { popupDictionaryWindow.innerHTML += defenitions[i] + "<br><br>" } range.insertNode(popupDictionaryWindow); }); popupVisible = true; } }La ventana emergente funciona, pero el texto en la ventana emergente también se resalta.
¿Alguien sabe cómo evitar que esto suceda? Soy nuevo en Javascript y, sinceramente, no entiendo completamente cómo funciona el rango de selección. Quiero dejar la palabra seleccionada resaltada, pero anular la selección de cualquier cosa en el nuevo intervalo emergente.
Encontré la solución. Todavía no entiendo del todo por qué tuve que hacer esto, pero la solución fue simplemente crear un nuevo rango en el mismo lugar que el anterior.
function insertPopupDict() { if (window.getSelection) { let selection = window.getSelection(); var text = selection.toString(); var range = selection.getRangeAt(0); //this is the solution to the highlight problem var newRange = document.createRange(); newRange.setStart(selection.focusNode, selection.startOffset); var popupDictionaryWindow = document.createElement('span'); popupDictionaryWindow.id = 'hawaiian-popup-dictionary' popupDictionaryWindow.style = 'margin-top: 35px; width: 360px;background-color: #555;color: #fff;text-align: center;border-radius: 6px;padding: 8px 0;position: absolute;z-index: 1;'; searchWord(text).then(defenitions => { popupDictionaryWindow.innerHTML = text + "<hr><br>"; for (var i = 0; i < defenitions.length; i++) { popupDictionaryWindow.innerHTML += defenitions[i] + "<br><br>" } //place node at newRange instead of range newRange.insertNode(popupDictionaryWindow); }); popupVisible = true; } }