我想将文本作为标签添加到我的网页并使其无法选择。
换句话说,当鼠标光标在文本上时,我希望它根本不变成文本选择光标。
我想要实现的一个很好的例子是这个网站上的按钮(问题、标签、用户......)
最佳答案
你不能用普通的普通 HTML 做到这一点,所以 JSF 在这里也不能为你做很多事情。
如果您的目标是 decent browsers只有,然后就使用 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>
如果您还想覆盖旧版浏览器,请考虑使用此 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>
如果您已经在使用 jQuery , 然后这是另一个例子,它向 jQuery 添加了一个新函数 disableSelection()
以便您可以在 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>
关于html - 如何使 HTML 文本不可选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2310734/