write bootstrap attribute javascript safari webkit textselection

javascript - bootstrap - title html attribute



Devolver HTML de un texto seleccionado por el usuario (3)

Tengo la siguiente página html, muy simple:

<html> <head> <script type="text/javascript"> function alertSelection() { var selection = window.getSelection(); var txt = selection.toString(); alert(txt); } </script> </head> <body> This is <span style="background-color:black;color:white">the</span> text. <div style="background-color:green;width:30px;height:30px;margin:30px" onmouseover="alertSelection()"> </body> </html>

Cuando selecciono la primera línea completa y muevo el mouse sobre el cuadrado, recibo una alerta con "Este es el texto".

¿Cómo solucionaría esto para que la etiqueta span o cualquier otro HTML seleccionado no se elimine del mensaje de alerta?

edición: estoy buscando específicamente cómo obtener el HTML completo de window.getSelection() . El cuadro de diálogo de alerta era cómo intentaba validar el código. Sólo me preocupa que esto funcione en Safari.


Aquí hay una función que le proporcionará el HTML correspondiente a la selección actual en todos los navegadores principales:

function getSelectionHtml() { var html = ""; if (typeof window.getSelection != "undefined") { var sel = window.getSelection(); if (sel.rangeCount) { var container = document.createElement("div"); for (var i = 0, len = sel.rangeCount; i < len; ++i) { container.appendChild(sel.getRangeAt(i).cloneContents()); } html = container.innerHTML; } } else if (typeof document.selection != "undefined") { if (document.selection.type == "Text") { html = document.selection.createRange().htmlText; } } return html; } alert(getSelectionHtml());


Los cuadros de alerta no muestran HTML, solo texto sin formato. No puede obtener el HTML para mostrar en un cuadro de alerta.

Lo que puede hacer es usar un reemplazo del cuadro de alerta JS en lugar de alert , como jQuery Dialog , un complemento de jQuery, o algo completamente distinto.