2010-02-24 101 views
71

我在HTML页面上有一个div,每当我按下鼠标并移动它时,它就会显示“不能放下”光标,就像它选择了一些东西。有没有办法禁用选择?我尝试CSS用户选择没有没有成功。防止在HTML中选择

回答

146

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 < 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")); 
+0

嗯,好像火狐3.6只能与-moz-前缀。 – Tower 2010-02-24 12:49:04

+0

它没有被选中,但仍然被复制到剪贴板(根据http://goo.gl/5P8uH的MDC规范) – ithkuil 2010-11-30 11:23:09

+0

@ithkuil:有趣的。看起来像“-moz-none”是要走的路。我会修改我的答案。 – 2010-11-30 12:15:28

1

你有某种透明的形象,你的选择吗?通常在拖动图像时会出现“无法放下”图标。否则,通常在拖动时选择文本。如果是这样,你可能必须使用z-index将图像放在所有东西后面。

5

我使用cancelBubble=truestopPropagation()在鼠标下移动处理程序。

+2

什么阻止我是,你需要它在_both_鼠标下来和移动处理程序,而不仅仅是移动! – 2012-07-24 01:06:30

10

这似乎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; 
    }); 
}); 
+0

我们可以使用此代码默认的所有图像? – 2015-05-07 10:10:32

+0

您可以使用“img”选择器,但要小心“event.preventDefault();”因为没有其他与“mousedown”相关的事件将在你的页面上工作... – molokoloco 2015-05-09 10:11:57

4

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); 
    }); 
}); 
+0

感谢您的这一点,在适当的方式上搜索了一段时间来阻止选择我的列表我阻止了点击,因为禁用的值不帖子.....哈哈 – thekevshow 2016-02-18 16:00:15