w3schools tag tab style page for color javascript events highlight detect

javascript - tag - title of page html



Javascript: cómo detectar si una palabra está resaltada (4)

Aquí hay un script:

<script language=javascript> function getSelText() {     var txt = '''';      if (window.getSelection)     {         txt = window.getSelection();              }     else if (document.getSelection)     {         txt = document.getSelection();             }     else if (document.selection)     {         txt = document.selection.createRange().text;             }     else return; document.aform.selectedtext.value = txt; } </script> <input type="button" value="Get selection" onmousedown="getSelText()"> <form name=aform > <textarea name="selectedtext" rows="5" cols="20"></textarea> </form>

Cortesía de Code Toad:

http://www.codetoad.com/javascript_get_selected_text.asp

En su caso, le conviene llamar a este script cuando se realice la selección, y luego puede procesarlo como lo desee, con una solicitud de AJAX para obtener información relevante, por ejemplo, como lo hace NYtimes.

Estoy escribiendo un complemento de Firefox que se activa cada vez que se resalta una palabra. Sin embargo, necesito un script que detecte cuándo se resalta una palabra, y estoy atascado. Un ejemplo sería nytimes.com (cuando estás leyendo un artículo y resaltas una palabra, aparece el ícono de referencia). Sin embargo, el script de nytimes.com es súper complejo. Tengo 16 años y no soy programador, así que definitivamente es una forma fuera de mi alcance.


Usando rangy.js y jQuery:

$(''#elem'').on(''keyup mouseup'', function(){ var sel = rangy.getSelection() if (sel.rangeCount === 0 || sel.isCollapsed) return alert(sel.toString()) })


Use el siguiente código

(function () { "use strict"; var showSelectedText = function (e) { var text = ''''; if (window.getSelection) { text = window.getSelection(); } else if (document.getSelection) { text = document.getSelection(); } else if (document.selection) { text = document.selection.createRange().text; } console.log(text.toString()); } document.onmouseup = showSelectedText; if (!document.all) { document.captureEvents(Event.MOUSEUP); } })();


La forma más fácil de hacerlo es detectar eventos de mouseup y keyup en el documento y verificar si se ha seleccionado algún texto. Lo siguiente funcionará en todos los principales navegadores.

Ejemplo: http://www.jsfiddle.net/timdown/SW54T/

function getSelectedText() { var text = ""; if (typeof window.getSelection != "undefined") { text = window.getSelection().toString(); } else if (typeof document.selection != "undefined" && document.selection.type == "Text") { text = document.selection.createRange().text; } return text; } function doSomethingWithSelectedText() { var selectedText = getSelectedText(); if (selectedText) { alert("Got selected text " + selectedText); } } document.onmouseup = doSomethingWithSelectedText; document.onkeyup = doSomethingWithSelectedText;