我正在构建一个HTML界面,其中包含一些文本元素,比如标签名称,在选定后看起来很糟糕。不幸的是,用户双击标签名称很容易在许多浏览器中默认将其选中。
我可能可以用JavaScript的技巧来解决这个问题(我也想看到那些答案)--但我真的希望有一些CSS/HTML直接适用于所有浏览器的方法。
我正在构建一个HTML界面,其中包含一些文本元素,比如标签名称,在选定后看起来很糟糕。不幸的是,用户双击标签名称很容易在许多浏览器中默认将其选中。
我可能可以用JavaScript的技巧来解决这个问题(我也想看到那些答案)--但我真的希望有一些CSS/HTML直接适用于所有浏览器的方法。
*.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;
-webkit-user-select:
应该放在-webkit-touch-callout:
之前。我没有验证过。 - Basil Bourque试一下这个:
<div onselectstart="return false">some stuff</div>
简单而有效...适用于所有主流浏览器的当前版本。
我使用此处所描述的CSS http://www.quirksmode.org/css/selection.html 取得了一定的成功:
::selection {
background-color: transparent;
}
它解决了我在AIR应用程序(WebKit引擎)中使用ThemeRoller ul
元素时遇到的大部分问题。仍然存在一个小的空白区域(约15 x 15),会被选中,但之前整个页面的一半都被选中。
display:box
、宽度和高度以及透明背景图像的锚元素来完成此操作。对于Safari浏览器,使用-khtml-user-select: none
,就像Mozilla的-moz-user-select
一样(或者在JavaScript中使用target.style.KhtmlUserSelect="none";
)。
// @usage use within a rule
// ex. img {@include user-select(none);}
// @param assumed valid user-select value
@mixin user-select($value)
{
& {
-webkit-touch-callout: $value;
-webkit-user-select: $value;
-khtml-user-select: $value;
-moz-user-select: $value;
-ms-user-select: $value;
user-select: $value;
}
}