【发布时间】:2011-01-20 12:37:08
【问题描述】:
我在 HTML 页面上有一个 div,每当我按下鼠标并移动它时,它都会显示“无法放下”光标,就像它选择了某些东西一样。有没有办法禁用选择?我尝试了没有成功的 CSS 用户选择。
【问题讨论】:
标签: javascript html selection
我在 HTML 页面上有一个 div,每当我按下鼠标并移动它时,它都会显示“无法放下”光标,就像它选择了某些东西一样。有没有办法禁用选择?我尝试了没有成功的 CSS 用户选择。
【问题讨论】:
标签: javascript html selection
我在鼠标向下和移动处理程序中使用cancelBubble=true 和stopPropagation()。
【讨论】:
event.preventDefault() 似乎可以解决问题(在 IE7-9 和 Chrome 中测试):
jQuery('#slider').on('mousedown', function (e) {
var handler, doc = jQuery(document);
e.preventDefault();
doc.on('mousemove', handler = function (e) {
e.preventDefault();
// refresh your screen here
});
doc.one('mouseup', function (e) {
doc.off('mousemove', handler);
});
});
【讨论】:
user-select 的专有变体适用于大多数现代浏览器:
*.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 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"));
【讨论】:
-moz-none 是要走的路。我会修改我的答案。
-moz-none 似乎不会被 Firebug 自动完成,尽管 none 是:-moz-user-select: none(有效)
user-select 只处理文本,不处理其他类型的元素
似乎 CSS 用户选择不会阻止图像拖放......所以......
HTML:
<img src="ico.png" width="20" height="20" alt="" unselectable="on" /> Blabla bla blabla
CSS:
* {
user-select: none;
-khtml-user-select: none;
-o-user-select: none;
-moz-user-select: -moz-none;
-webkit-user-select: none;
}
::selection { background: transparent;color:inherit; }
::-moz-selection { background: transparent;color:inherit; }
JS:
$(function(){
$('*:[unselectable=on]').mousedown(function(event) {
event.preventDefault();
return false;
});
});
【讨论】:
您选择了某种透明图像吗?当您拖动图像时,通常会出现“无法放置”图标。否则,它通常会在您拖动时选择文本。如果是这样,您可能必须使用 z-index 将图像放在所有内容的后面。
【讨论】: