【问题标题】:disable text selection except input禁用除输入外的文本选择
【发布时间】:2019-07-06 14:38:39
【问题描述】:

我有这个 sn-p 代码来禁用所有文本选择。我将如何禁用除输入之外的所有文本?我尝试了$('* :not(input)').disableTextSelect();,但它禁用了所有内容的选择(包括输入)

$.extend($.fn.disableTextSelect = function () {
                return this.each(function () {
                    if ($.browser.mozilla) {//Firefox
                        $(this).css('MozUserSelect', 'none');
                    } else if ($.browser.msie) {//IE
                        $(this).bind('selectstart', function () { return false; });
                    } else {//Opera, etc.
                        $(this).mousedown(function () { return false; });
                    }
                });
            });
            $('* :not(input)').disableTextSelect(); 

【问题讨论】:

  • 您确定 * 是必要的吗?试试 $(":not(input)")
  • 请注意,禁用选择会改变浏览器的默认行为,并且会混淆甚至惹恼用户。

标签: javascript jquery


【解决方案1】:
$(document).bind('mousedown selectstart', function(e) {
    return $(e.target).is('input, textarea, select, option, html');
});

感谢@user2873592,他提到在这里添加html可以解决chrome滚动条无法拖动的问题。

【讨论】:

  • 刚刚将它粘贴到 document.ready 中,它就像一个魅力!非常感谢@deerchao
【解决方案2】:

这适用于 IE 和 FF:

    jQuery(document).ready(function () {
        //Disable default text selection behavior
        toggleEnableSelectStart(false);

        //for inputs it must be possible to select text
        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); });

    });

    function toggleEnableSelectStart(enable) {
        document.onmousedown = function (e) { return enable; };
        document.onselectstart = function (e) { return enable; }; ;
    }

【讨论】:

  • 在 IE、FF、Opera 和 Chrome 中为我工作
【解决方案3】:

问题似乎是这种禁用是继承的。因此,即使您没有在 $() 中选择它们,它们仍然会被禁用。但这也可能对我们有利。

禁用后,您可以启用输入。

$('body').css('MozUserSelect', '-moz-none');
$('input').css('MozUserSelect', 'text');

注意:该值必须是“-moz-none”。如果为“无”,则无法更改。

我无法测试 IE,也没有针对 Opera 的解决方案。但也许这会有所帮助。

【讨论】:

    猜你喜欢
    • 2022-09-23
    • 2017-08-09
    • 2016-12-21
    • 2014-05-11
    • 1970-01-01
    • 1970-01-01
    • 2018-07-21
    • 1970-01-01
    • 2019-02-19
    相关资源
    最近更新 更多