如何使HTML文不可选择[重复]
-
22-09-2019 - |
题
这个问题已经有一个答案在这里:
- 如何禁用文本的突出显示选择 41答案
我想添加文字到我的网页作为一个标签,并使其不可选择.
换句话说,当鼠标是通过该文本,我希望它不会变成一文本的选择标。
一个很好的例子是我想要实现的按钮上这个网站(问题、标签、用户...)
解决方案
你不能这么用普通HTML,因此JSF不能做很多你在这里。
如果你的目标 体面的浏览器 只,那么就使用的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, 然后这里的另一个例子,其中增加了一个新的功能 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>
其他提示
没有人在这里发表的答复以所有的正确的CSS变化,所以这里是:
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
完全现代的解决你的问题是纯粹基于CSS,但注意到,旧的浏览器就不支持它,在这种情况下你需要后退到解决方案,例如其他人已经提供。
因此,在纯CSS:
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
-o-user-select: none;
user-select: none;
但是鼠标仍然会变为一个插入符当的元件的文本,因此添加:
cursor: default;
现代CSS是很优雅。
我改变s插件张贴上面,所以它将在工作生活的元素。
(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);
然后你可以这么喜欢的东西:
$(document).ready(function() {
$('label').disableSelection();
// Or to make everything unselectable
$('*').disableSelection();
});
不隶属于 StackOverflow