javascript - 如何在不突出显示/选择文本的情况下单击其中包含文本的 div

标签 javascript jquery css

<分区>

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如果你连续点击几次 + 按钮,它有时看起来像这样:

enter image description here

如果用户连续单击其中一个按钮,是否有办法防止文本被选中/突出显示?谢谢!

最佳答案

您可以使用 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);

关于javascript - 如何在不突出显示/选择文本的情况下单击其中包含文本的 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14654591/

相关文章:

javascript - 根据值自定义颜色(多次)

jquery - 无法从网页写入 XML

javascript - JQuery UI 自动完成选择返回未定义

javascript - 如果另一个元素为空,如何动态隐藏 html 元素

javascript - document.create 未加载脚本,未向 JS 文件发出请求

jquery - 选择节点上的 jsTree ajax 加载指示器 (MVC 4.0)

javascript - 如何检查同位素是否已初始化?

javascript - 有条件地更改去抖执行延迟

javascript - 为什么这个表的最后一列太宽了?

javascript - 我怎样才能同时去锚定和打开 Bootstrap Accordion ?