在項目中使用 jQuery UI 的 disableSelection() 方法禁止某容器內的文字選取,但在 Firefox 中導致該容器內的 <select> 下拉框點擊無法彈出選項。IE 和 Chrome 正常。
disableSelection() 內部綁定 mousedown 事件並調用 preventDefault() 來阻止默認選取行為。Firefox 對 <select> 的 mousedown 事件極其敏感,阻止默認行為會直接屏蔽下拉彈出的原生交互。
// 對整個容器禁用選取
$("#container").disableSelection();
// 容器內有 select
//
//
//
// 1. 針對非 select 元素禁用選取
$("#container").find(":not(select)").disableSelection();
// 2. 或在 disableSelection 後恢復 select 的 mousedown
$("#container").disableSelection();
$("#container select").off("mousedown.disableSelection"); // 移除特定命名空間事件
.no-select {
-webkit-user-select: none; /* Chrome/Safari */
-moz-user-select: none; /* Firefox */
-ms-user-select: none; /* IE10+ */
user-select: none; /* 標準 */
}
/* 但允許 select 正常交互 */
.no-select select {
-webkit-user-select: auto;
-moz-user-select: auto;
-ms-user-select: auto;
user-select: auto;
}
HTML:<div class="no-select">...</div>
$("#container").on("mousedown", function(e) {
// 忽略 select、option、input、textarea 等交互元素
var tag = e.target.tagName.toLowerCase();
if (['select', 'option', 'input', 'textarea', 'button', 'a'].indexOf(tag) === -1) {
e.preventDefault();
}
});
// 簡化版
$.fn.disableSelection = function() {
return this.bind(( $.support.selectstart ? "selectstart" : "mousedown" ) +
".ui-disableSelection", function(e) {
e.preventDefault();
});
};
可見它在 mousedown 或 selectstart 上阻止默認行為,Firefox 下 select 依賴 mousedown 打開下拉列表,故受影響。
user-select: none:無 JS 開銷、不干擾表單元素、現代瀏覽器全支援jQuery UI 的 disableSelection() 是早期解決拖拽時誤選文本的方案,但副作用明顯。現代開發應全面遷移至 CSS user-select,並配合精確的事件過濾,保障表單交互元素正常工作。