有没有办法使文本在HTML页面上不可选? [英] Is there a way to make text unselectable on an HTML page?
问题描述
我正在建立一个HTML用户界面,其中包含一些文本元素,例如标签名称,在选中时显示为不良。不幸的是,用户很容易双击某个标签名称,默认情况下会在许多浏览器中进行选择。
I'm building an HTML UI with some text elements, such as tab names, which look bad when selected. Unfortunately, it's very easy for a user to double-click a tab name, which selects it by default in many browsers.
我可以使用JavaScript来解决这个问题(我想看看这些答案) - 但我真的希望有一些CSS / HTML直接适用于所有浏览器。
I might be able to solve this with a JavaScript trick (I'd like to see those answers, too) -- but I'm really hoping there's something in CSS/HTML directly that works across all browsers.
推荐答案
在大多数浏览器中,这可以使用CSS实现:
In most browsers, this can be achieved using CSS:
*.unselectable {
-moz-user-select: -moz-none;
-khtml-user-select: none;
-webkit-user-select: none;
/*
Introduced in IE 10.
See http://ie.microsoft.com/testdrive/HTML5/msUserSelect/
*/
-ms-user-select: none;
user-select: none;
}
< 10和Opera,您将需要使用您希望不可选择的元素的 unselectable
属性。您可以使用HTML中的属性设置此属性:
For IE < 10 and Opera, you will need to use the unselectable
attribute of the element you wish to be unselectable. You can set this using an attribute in HTML:
<div id="foo" unselectable="on" class="unselectable">...</div>
很遗憾,这个属性没有继承,意味着你必须在每个元素在< div>
中。如果这是一个问题,你可以使用JavaScript递归地为一个元素的后代:
Sadly this property isn't inherited, meaning you have to put an attribute in the start tag of every element inside the <div>
. If this is a problem, you could instead use JavaScript to do this recursively for an element's descendants:
function makeUnselectable(node) {
if (node.nodeType == 1) {
node.setAttribute("unselectable", "on");
}
var child = node.firstChild;
while (child) {
makeUnselectable(child);
child = child.nextSibling;
}
}
makeUnselectable(document.getElementById("foo"));
这篇关于有没有办法使文本在HTML页面上不可选?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!