Possible Duplicate:
What is the best way to prevent highlighting of text when clicking on its containing div in javascript?
我正在使用 +
和 -
文本按钮 (divs) 构建我自己的简单计数器。我有它在另一个 div 上执行 .focus() 的地方,.countDisplay
应该将焦点从 计数按钮上移开。最好的例子:http://jsbin.com/uxewej/2/edit如果你连续点击几次 +
按钮,它有时看起来像这样:
如果用户连续单击其中一个按钮,是否有办法防止文本被选中/突出显示?谢谢!
您可以使用 CSS 来解决这个问题:http://jsbin.com/uxewej/8/
html{
-webkit-user-select:none;
-khtml-user-select:none;
-moz-user-select:none;
-ms-user-select:none;
user-select:none;
}
如果您需要让用户选择某些内容,请不要使用 html
CSS 选择器。
更新
使用 FF、Chrome 和 IE9 测试
补充 CSS 声明的通用解决方案
function toggleEnableSelectStart(enable) {
document.onmousedown = function (e) { return enable; };
document.onselectstart = function (e) { return enable; };
}
jQuery(document).ready(function () {
//Disable default text selection behavior
toggleEnableSelectStart(false);
//Let inputs text selection possible
jQuery("input[type=text]").focusin(function () { toggleEnableSelectStart(true); });
jQuery("input[type=text]").mouseover(function () { toggleEnableSelectStart(true); });
jQuery("input[type=text]").focusout(function () { toggleEnableSelectStart(false); });
jQuery("input[type=text]").mouseout(function () { toggleEnableSelectStart(false); });
});
对不起作者,我不记得有一天我在哪里找到的,但它很聪明!
更新 2
要避免仅在您的按钮上单击选择行为,请删除 CSS 技巧并使用
http://jsbin.com/uxewej/11/edit
function toggleEnableSelectStart(enable) {
document.onmousedown = function (e) { return enable; };
document.onselectstart = function (e) { return enable; };
}
jQuery(document).ready(function () {
//Disable default text selection behavior
toggleEnableSelectStart(false);
//Let inputs text selection possible
jQuery(".countButton").focusin(function () { toggleEnableSelectStart(false); });
jQuery(".countButton").mouseover(function () { toggleEnableSelectStart(false); });
jQuery(".countButton").focusout(function () { toggleEnableSelectStart(true); });
jQuery(".countButton").mouseout(function () { toggleEnableSelectStart(true); });
});
更新 3
如果你想禁用所选元素的选择,请遵循 this link
(function($){
$.fn.disableSelection = function() {
return this
.attr('unselectable', 'on')
.css('user-select', 'none')
.on('selectstart', false);
};
})(jQuery);