Pregunta

    

Esta pregunta ya tiene una respuesta aquí:

         

Me gustaría añadir texto a mi página web como una etiqueta y que sea seleccionable.

En otras palabras, cuando el cursor del ratón sobre el texto me gustaría que se convierta en un cursor de texto Selección en absoluto.

Un buen ejemplo de lo que estoy tratando de lograr es los botones de esta página web (Preguntas, las etiquetas, los usuarios, ...)

¿Fue útil?

Solución

No se puede hacer esto con HTML con sabor de vainilla, así JSF no puede hacer mucho para usted aquí también.

Si usted está apuntando navegadores decentes solamente, a continuación, sólo hacen uso de CSS3 :

.unselectable {
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}
<label class="unselectable">Unselectable label</label>

Si desea cubrir los navegadores más antiguos, así, entonces considerar este JavaScript retorno:

<!doctype html>
<html lang="en">
    <head>
        <title>SO question 2310734</title>
        <script>
            window.onload = function() {
                var labels = document.getElementsByTagName('label');
                for (var i = 0; i < labels.length; i++) {
                    disableSelection(labels[i]);
                }
            };
            function disableSelection(element) {
                if (typeof element.onselectstart != 'undefined') {
                    element.onselectstart = function() { return false; };
                } else if (typeof element.style.MozUserSelect != 'undefined') {
                    element.style.MozUserSelect = 'none';
                } else {
                    element.onmousedown = function() { return false; };
                }
            }
        </script>
    </head>
    <body>
        <label>Try to select this</label>
    </body>
</html>

Si usted ya está usando jQuery , entonces aquí es otro ejemplo que añade una nueva función para disableSelection() jQuery, para que pueda utilizarlo en cualquier lugar en el código jQuery:

<!doctype html>
<html lang="en">
    <head>
        <title>SO question 2310734 with jQuery</title>
        <script src="http://code.jquery.com/jquery-latest.min.js"></script>
        <script>
            $.fn.extend({ 
                disableSelection: function() { 
                    this.each(function() { 
                        if (typeof this.onselectstart != 'undefined') {
                            this.onselectstart = function() { return false; };
                        } else if (typeof this.style.MozUserSelect != 'undefined') {
                            this.style.MozUserSelect = 'none';
                        } else {
                            this.onmousedown = function() { return false; };
                        }
                    }); 
                } 
            });

            $(document).ready(function() {
                $('label').disableSelection();            
            });
        </script>
    </head>
    <body>
        <label>Try to select this</label>
    </body>
</html>

Otros consejos

Aquí nadie ha publicado una respuesta con todas las variaciones CSS correctos, por lo que aquí es:

-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;

La solución moderna llena a su problema es puramente basado en CSS, pero tenga en cuenta que los navegadores antiguos no lo apoyarán, en el que los casos que había necesidad de repliegue a soluciones como las que otros han proporcionado.

Así que en puro CSS:

-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
-o-user-select: none;
user-select: none;

Sin embargo, el cursor del ratón todavía cambiar a un cursor cuando más del texto del elemento, por lo que se agrega a lo siguiente:

cursor: default;

CSS moderna es bastante elegante.

Me alteró el plugin de jQuery publicado por encima de lo que sería trabajar en elementos vivos.

(function ($) {
$.fn.disableSelection = function () {
    return this.each(function () {
        if (typeof this.onselectstart != 'undefined') {
            this.onselectstart = function() { return false; };
        } else if (typeof this.style.MozUserSelect != 'undefined') {
            this.style.MozUserSelect = 'none';
        } else {
            this.onmousedown = function() { return false; };
        }
    });
};
})(jQuery);

A continuación, podría así que algo como:

$(document).ready(function() {
    $('label').disableSelection();

    // Or to make everything unselectable
    $('*').disableSelection();
});
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top