NueveReinas
HTML
<p>Esto texto no se marcará.</p>
<div class="miTexto">Si seleccionas este texto, se marcará.</div>
<span>BLA BLA BLA, aquí no hay marca si lo seleccionas.</span>
<div class="miTexto"><p>Selecciona esto :)</p></div>
CSS
/* Esto te marca la selección actual */
*::selection {
color:black;
background:red;
}
/* Este es el estilo que se le va a agregar al texto seleccionado */
.marca {
color:black;
background:yellow;
}
JavaScript
$(".miTexto").on("mouseup", function (e) { //Importante trabajar con clases y NO con IDs
var selected = getSelection();
var range = selected.getRangeAt(0);
console.log(range);
if(selected.toString().length >= 1){ //Si se seleccionan uno o más caracteres...
var newNode = document.createElement("span"); //Crea un span
newNode.setAttribute("class", "marca"); //Le añade la clase
range.surroundContents(newNode);
}
selected.removeAllRanges();
});
function getSelection() {
var seltxt = '';
if (window.getSelection) {
seltxt = window.getSelection();
} else if (document.getSelection) {
seltxt = document.getSelection();
} else if (document.selection) {
seltxt = document.selection.createRange().text;
}
else return;
return seltxt;
}