Tyl*_*ler 140 html javascript css cross-browser textselection
我正在构建一个包含一些文本元素的HTML UI,例如选项卡名称,这些元素在选中时看起来很糟糕.不幸的是,用户很容易双击选项卡名称,默认情况下会在许多浏览器中选择它.
我或许可以通过JavaScript技巧来解决这个问题(我也希望看到这些答案) - 但我真的希望CSS/HTML中的某些东西直接适用于所有浏览器.
Tim*_*own 190
在大多数浏览器中,这可以使用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;
}
Run Code Online (Sandbox Code Playgroud)
对于IE <10和Opera,您需要使用unselectable您希望不可选择的元素的属性.您可以使用HTML中的属性进行设置:
<div id="foo" unselectable="on" class="unselectable">...</div>
Run Code Online (Sandbox Code Playgroud)
遗憾的是,这个属性不是继承的,这意味着你必须在一个内部的每个元素的开始标记中放置一个属性<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"));
Run Code Online (Sandbox Code Playgroud)
dim*_*ist 41
<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>
Run Code Online (Sandbox Code Playgroud)
编辑
代码显然来自http://www.dynamicdrive.com
Blo*_*sie 33
所有正确的CSS变体都是:
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
Run Code Online (Sandbox Code Playgroud)
Ste*_*edd 13
试试这个:
<div onselectstart="return false">some stuff</div>
Run Code Online (Sandbox Code Playgroud)
简单但有效......适用于所有主流浏览器的当前版本.
我发现这里描述的CSS有一定程度的成功http://www.quirksmode.org/css/selection.html:
::selection {
background-color: transparent;
}
Run Code Online (Sandbox Code Playgroud)
它解决了我ul在AIR应用程序(WebKit引擎)中使用一些ThemeRoller 元素时遇到的大多数问题.仍然会得到一个小的(大约15 x 15)虚拟补丁被选中,但之前选择了一半的页面.
| 归档时间: |
|
| 查看次数: |
105816 次 |
| 最近记录: |