我正在构建一个带有一些文本元素的 HTML UI,例如选项卡名称,这些元素在选择时看起来很糟糕。不幸的是,用户很容易双击选项卡名称,在许多浏览器中默认选择它。
我也许可以用 JavaScript 技巧来解决这个问题(我也想看看这些答案)——但我真的希望 CSS/HTML 中有一些直接适用于所有浏览器的东西。
我正在构建一个带有一些文本元素的 HTML UI,例如选项卡名称,这些元素在选择时看起来很糟糕。不幸的是,用户很容易双击选项卡名称,在许多浏览器中默认选择它。
我也许可以用 JavaScript 技巧来解决这个问题(我也想看看这些答案)——但我真的希望 CSS/HTML 中有一些直接适用于所有浏览器的东西。
在大多数浏览器中,这可以使用 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;
}
对于 IE < 10 和 Opera,您将需要使用unselectable
您希望不可选的元素的属性。您可以使用 HTML 中的属性进行设置:
<div id="foo" unselectable="on" class="unselectable">...</div>
遗憾的是,此属性不是继承的,这意味着您必须在<div>
. 如果这是一个问题,您可以改为使用 JavaScript 为元素的后代递归执行此操作:
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"));
<script type="text/javascript">
/***********************************************
* Disable Text Selection script- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
***********************************************/
function disableSelection(target){
if (typeof target.onselectstart!="undefined") //IE route
target.onselectstart=function(){return false}
else if (typeof target.style.MozUserSelect!="undefined") //Firefox route
target.style.MozUserSelect="none"
else //All other route (ie: Opera)
target.onmousedown=function(){return false}
target.style.cursor = "default"
}
//Sample usages
//disableSelection(document.body) //Disable text selection on entire body
//disableSelection(document.getElementById("mydiv")) //Disable text selection on element with id="mydiv"
</script>
编辑
所有正确的 CSS 变体是:
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
试试这个:
<div onselectstart="return false">some stuff</div>
简单但有效...适用于所有主要浏览器的当前版本。