【问题标题】:How to disable text selection using jQuery?如何使用 jQuery 禁用文本选择?
【发布时间】:2011-02-11 14:26:48
【问题描述】:

jQuery 或 jQuery-UI 是否有任何功能可以禁用给定文档元素的文本选择?

【问题讨论】:

  • @John:上面的链接能回答你的问题吗?如果没有,您可能需要更详细地说明您的情况有何不同。
  • 是的。但是,虽然答案是一样的,但这个问题非常具体,所以很多人在考虑更一般的问题时会错过这个答案(就像我一样)。
  • @Jhon:另一个问题也有jQuery解决方案。

标签: javascript jquery jquery-ui


【解决方案1】:

在 jQuery 1.8 中,可以按如下方式完成:

(function($){
    $.fn.disableSelection = function() {
        return this
                 .attr('unselectable', 'on')
                 .css('user-select', 'none')
                 .on('selectstart', false);
    };
})(jQuery);

【讨论】:

  • JavaScript 替代方案仅适用于 IE。 “onselectstart”不适用于其他浏览器
  • @Omar:我很清楚这一点。
  • 谢谢。我正在研究一个拖动滑块,需要一种在此过程中不会选择文本的方法。
  • 对于那些说“只是不要”禁用文本选择(或其他任何关于此问题的内容)的人,请稍微敞开心扉。很多时候人们出于审美原因禁用它,例如避免在双击带有文本的标签时选择文本等。所以要么回答这个问题,要么提供一个实际的反驳点并指定你在说什么否定,不要不要只是笼统地勾勒出这个想法。
【解决方案2】:

我发现这个答案 (Prevent Highlight of Text Table) 最有帮助,也许它可以与提供 IE 兼容性的另一种方式结合使用。

#yourTable
{
  -moz-user-select: none;
  -khtml-user-select: none;
  -webkit-user-select: none;
  user-select: none;
}

【讨论】:

  • Chrome 使用 -webkit-user-select
  • 总是欣赏 CSS 做事的方式,而不是一般使用 jQuery 或 JS。就像 jQuery 动画 vs CSS 过渡一样,内置到浏览器中的方式总是最好和最有效的。
【解决方案3】:

如果你使用 jQuery UI,有一个方法可以解决这个问题,但它只能处理鼠标选择(即 CTRL+A 仍然有效):

$('.your-element').disableSelection(); // deprecated in jQuery UI 1.9

代码很简单,如果你不想使用jQuery UI:

$(el).attr('unselectable','on')
     .css({'-moz-user-select':'-moz-none',
           '-moz-user-select':'none',
           '-o-user-select':'none',
           '-khtml-user-select':'none', /* you could also put this in a class */
           '-webkit-user-select':'none',/* and add the CSS class here instead */
           '-ms-user-select':'none',
           'user-select':'none'
     }).bind('selectstart', function(){ return false; });

【讨论】:

  • jquery ui 功能会很棒,但它没有提供相同级别的保护,它确实可以防止直接选择事物,但是如果您携带来自另一个 dom 对象的选择,则需要css 规则也是 - 继承了 function = function () { return this.bind( ( $.support.selectstart ? "selectstart" : "mousedown" ) + ".ui-disableSelection", function( event ) { event.preventDefault( ); }); }
  • 请注意,在 jQuery UI 1.9 中不推荐使用 disableSelection()
  • 它可能还需要 .on('mousedown', false) 才能工作,具体取决于您的浏览器。但是,默认情况下杀死 mousedown 事件是很危险的,因为这可能会破坏现有功能
  • 精氨酸。被贬值了,很烦。你有足够的时间合法地想要这个。
  • 我正在一些锚文本上创建一个右键单击上下文菜单,我不希望文本在单击时选择。所以是的,@Monk,这可以作为一个合法的例子。
【解决方案4】:

这里有一个比较全面的断开选择的解决方案,取消部分热键(如Ctrl+aCtrl+c.Test: Cmd+aCmd+c)

(function($){

  $.fn.ctrlCmd = function(key) {

    var allowDefault = true;

    if (!$.isArray(key)) {
       key = [key];
    }

    return this.keydown(function(e) {
        for (var i = 0, l = key.length; i < l; i++) {
            if(e.keyCode === key[i].toUpperCase().charCodeAt(0) && e.metaKey) {
                allowDefault = false;
            }
        };
        return allowDefault;
    });
};


$.fn.disableSelection = function() {

    this.ctrlCmd(['a', 'c']);

    return this.attr('unselectable', 'on')
               .css({'-moz-user-select':'-moz-none',
                     '-moz-user-select':'none',
                     '-o-user-select':'none',
                     '-khtml-user-select':'none',
                     '-webkit-user-select':'none',
                     '-ms-user-select':'none',
                     'user-select':'none'})
               .bind('selectstart', false);
};

})(jQuery);

并调用示例:

$(':not(input,select,textarea)').disableSelection();

jsfiddle.net/JBxnQ/

这对于旧版本的 FireFox 也可能不够(我不知道是哪个)。如果这一切都不起作用,请添加以下内容:

.on('mousedown', false)

【讨论】:

  • 为什么要给attr('unselectable', 'on')打两次电话?是错字还是有用?
  • 这对我很有用,但我不得不禁用 ".each(function() { $(this).attr('unselectable','on') .bind('selectstart',函数(){返回假;});});“我的特定网络应用程序(JQuery Mobile)的部分,以防万一它可以帮助任何人..
【解决方案5】:

这可以使用 JavaScript 轻松完成,适用于所有浏览器

<script type="text/javascript">

/***********************************************
* Disable Text Selection script- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
***********************************************/

function disableSelection(target){
if (typeof target.onselectstart!="undefined") //For IE 
    target.onselectstart=function(){return false}
else if (typeof target.style.MozUserSelect!="undefined") //For Firefox
    target.style.MozUserSelect="none"
else //All other route (For Opera)
    target.onmousedown=function(){return false}
target.style.cursor = "default"
}
 </script>

调用此函数

<script type="text/javascript">
   disableSelection(document.body)
</script>

【讨论】:

  • 这个太棒了!但是我们如何停止对它的“关注”呢?
  • 这个答案在 2013 年已经过时了
【解决方案6】:

CHROME 的 1 行解决方案:

body.style.webkitUserSelect = "none";

和FF:

body.style.MozUserSelect = "none";

IE 需要设置“不可选择”属性(详情在底部)。

我在 Chrome 中对此进行了测试,它可以正常工作。此属性是继承的,因此在 body 元素上设置它会禁用整个文档中的选择。

详情请看:http://help.dottoro.com/ljrlukea.php

如果您使用 Closure,只需调用此函数:

goog.style.setUnselectable(myElement, true);

它透明地处理所有浏览器。

非IE浏览器是这样处理的:

goog.style.unselectableStyle_ =
    goog.userAgent.GECKO ? 'MozUserSelect' :
    goog.userAgent.WEBKIT ? 'WebkitUserSelect' :
    null;

在这里定义: http://closure-library.googlecode.com/svn/!svn/bc/4/trunk/closure/goog/docs/closure_goog_style_style.js.source.html

IE 部分的处理方式如下:

if (goog.userAgent.IE || goog.userAgent.OPERA) {
// Toggle the 'unselectable' attribute on the element and its descendants.
var value = unselectable ? 'on' : '';
el.setAttribute('unselectable', value);
if (descendants) {
  for (var i = 0, descendant; descendant = descendants[i]; i++) {
    descendant.setAttribute('unselectable', value);
  }
}

【讨论】:

    【解决方案7】:
            $(document).ready(function(){
                $("body").css("-webkit-user-select","none");
                $("body").css("-moz-user-select","none");
                $("body").css("-ms-user-select","none");
                $("body").css("-o-user-select","none");
                $("body").css("user-select","none");
            });
    

    【讨论】:

    • 除了代码之外,能不能把答案的简要总结一下?
    【解决方案8】:

    我认为这段代码适用于所有浏览器并且需要最少的开销。它实际上是上述所有答案的混合体。如果您发现错误,请告诉我!

    添加 CSS:

    .no_select { user-select: none; -o-user-select: none; -moz-user-select: none; -khtml-user-select: none; -webkit-user-select: none; -ms-user-select:none;}
    

    添加 jQuery:

    (function($){
        $.fn.disableSelection = function() 
        {       
            $(this).addClass('no_select');              
            if($.browser.msie)
            {
                $(this).attr('unselectable', 'on').on('selectstart', false);            
            }
        return this;            
    };
    })(jQuery);
    

    可选:要同时禁用所有子元素的选择,您可以将 IE 块更改为:

    $(this).each(function() {
        $(this).attr('unselectable','on')
        .bind('selectstart',function(){ return false; });
    });
    

    用法:

    $('.someclasshere').disableSelection();
    

    【讨论】:

      【解决方案9】:

      以下将禁用所有常见浏览器(IE、Chrome、Mozilla、Opera 和 Safari)中所有类“项目”的选择:

      $(".item")
              .attr('unselectable', 'on')
              .css({
                  'user-select': 'none',
                  'MozUserSelect': 'none'
              })
              .on('selectstart', false)
              .on('mousedown', false);
      

      【讨论】:

      • 并不复杂 - 太棒了!谢谢你。适合残疾人看;我添加了 .attr('disabled', 'disabled')
      • 更新:我使用 .attr('readonly', 'readonly') 代替 .attr('disabled', 'disabled')。禁用可防止在 MVC 中发布我的模型变量(模型变量为空)。 Readonly 仍然禁用查找(我使用引导程序),它允许发布项目值
      • 优秀的兄弟,我使用此代码替换“指针事件:无;”,这在 IE 11 中不起作用。问候
      【解决方案10】:

      这其实很简单。 要禁用文本选择(以及单击+拖动文本(例如 Chrome 中的链接)),只需使用以下 jQuery 代码:

      $('body, html').mousedown(function(event) {
          event.preventDefault();
      });
      

      所有这一切都是为了防止在您用鼠标 (mousedown()) 在 bodyhtml 标记中单击时发生默认设置。您只需更改两个引号之间的文本即可非常轻松地更改元素(例如,将 $('body, html') 更改为 $('#myUnselectableDiv') 以使 myUnselectableDiv div 不可选择。

      向您展示/证明这一点的快速 sn-p:

      $('#no-select').mousedown(function(event) {
        event.preventDefault();
      });
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
      <span id="no-select">I bet you can't select this text, or drag <a href="#">this link</a>, </span>
      <br/><span>but that you can select this text, and drag <a href="#">this link</a>!</span>

      请注意,这种效果并不完美,在使整个窗口不可选的同时表现最佳。您可能还想添加

      取消部分热键(如Ctrl+aCtrl+cTest:Cmd+aCmd+c)

      同样,通过使用上述弗拉基米尔答案的那一部分。 (去他的帖子here

      【讨论】:

        【解决方案11】:

        我找到它的最好和最简单的方法,防止 ctrl + c,右键单击。在这种情况下,我阻止了所有内容,因此我不必指定任何内容。

        $(document).bind("contextmenu cut copy",function(e){
            e.preventDefault();
            //alert('Copying is not allowed');
        });
        

        【讨论】:

          【解决方案12】:

          在适当的情况下,对此的一种解决方案是使用&lt;button&gt; 来表示您不想选择的文本。如果您绑定到某个文本块上的 click 事件,并且不希望该文本是可选的,将其更改为按钮将改善语义并防止文本被选中。

          <button>Text Here</button>
          

          【讨论】:

            【解决方案13】:

            我已经尝试了所有方法,这对我来说是最简单的,因为我使用的是 IWebBrowser2 并且没有 10 个浏览器可以应对:

            document.onselectstart = new Function('return false;');
            

            非常适合我!

            【讨论】:

              猜你喜欢
              • 2011-12-02
              • 1970-01-01
              • 2013-09-09
              • 2010-10-27
              • 2015-12-19
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多