2010-02-24 100 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