2009-05-28 68 views
1

我想創建一個文本按鈕,使用簡單的跨度和格式化文本並提供onclick行爲。問題出在用戶點擊按鈕時,有時會突出顯示按鈕的文本。Javascript/CSS禁用文本選擇

我想避免這種行爲,因爲它在選擇文本時看起來非常醜陋。任何CSS/JavaScript /(jQuery)我可以用來避免這種情況?

非常感謝您的時間。

+0

當所有提及的javascript後綴爲「jquery」時,我都會看到並微笑。有時候我覺得社區已經與傳統的javascript脫節了。 – jrharshath 2009-05-28 09:54:47

+0

我不是嘿嘿 – Ropstah 2009-05-28 09:56:01

+0

[CSS規則禁用文本選擇突出顯示]的可能的重複(http://stackoverflow.com/questions/826782/css-rule-to-disable-text-selection-highlighting) – Dan 2013-07-18 08:57:19

回答

6
spanid.onselectstart = function() {return false;} // ie 
spanid.onmousedown = function() {return false;} // mozilla 
在谷歌

第一個結果的方式......

額外

$('#spanid').selectstart(function(event) { 
    event.preventDefault(); 
}); 
+0

jQuery也是非常不錯:看帖子.. – Ropstah 2009-05-28 09:54:44

+0

+1這樣一個簡單的解決方案:)我沒有意識到這將是這個簡單的 – jrharshath 2009-05-28 09:57:42

1

你可以這樣寫:

$('#spanid').disableSelection(); 
+1

只是澄清,這需要jQuery庫。 – dwaz 2011-03-19 19:06:05

5

的CSS解決方案:

.unselectable { 
    -webkit-touch-callout: none; 
    -webkit-user-select: none; 
    -khtml-user-select: none; /* Isn't Konquerour dead? */ 
    -moz-user-select: -moz-none; 
    -moz-user-select: none; 
    -ms-user-select: none; 
    user-select: none; 
} 

但是,looking here,CSS解決方案在2013年末還不夠,所以你應該添加一些javascript。周圍有很好的答案。