Como tornar o texto html inocente [duplicado
-
22-09-2019 - |
Pergunta
Esta pergunta já tem uma resposta aqui:
- Como desativar a seleção de texto destacando 41 respostas
Gostaria de adicionar texto à minha página da web como uma etiqueta e torná -la inigualável.
Em outras palavras, quando o cursor do mouse está acima do texto, eu gostaria que não se transforme em um texto selecionando o cursor.
Um bom exemplo do que estou tentando alcançar são os botões deste site (perguntas, tags, usuários, ...)
Solução
Você não pode fazer isso com HTML de baunilha simples, então o JSF não pode fazer muito por você aqui também.
Se você está segmentando navegadores decentes Somente, basta usar o 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>
Se você deseja cobrir os navegadores mais antigos também, considere este fallback de JavaScript:
<!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>
Se você já está usando jQuery, então aqui está outro exemplo que adiciona uma nova função disableSelection()
para jQuery para que você possa usá -lo em qualquer lugar do seu 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>
Outras dicas
Ninguém aqui postou uma resposta com todas as variações corretas do CSS, então aqui está:
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
A solução moderna completa para o seu problema é puramente baseada em CSS, mas observe que os navegadores mais antigos não o apoiarão; em que casos você precisaria de fallback de soluções como as outras forneceram.
Então, em CSS puro:
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
-o-user-select: none;
user-select: none;
No entanto, o cursor do mouse ainda mudará para um intercalado quando estiver acima do texto do elemento, então você adiciona a isso:
cursor: default;
O CSS moderno é bastante elegante.
Alterei o plugin jQuery postado acima para que ele funcionasse em elementos ao vivo.
(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);
Então você poderia tão algo como:
$(document).ready(function() {
$('label').disableSelection();
// Or to make everything unselectable
$('*').disableSelection();
});