如何使用jQuery禁用文本选择?

Daw*_*hia 197 javascript jquery jquery-ui

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

SLa*_*aks 272

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

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

  • 对于那些说"只是不"禁用文本选择的人(或其他任何关于此事的东西),请稍微打开你的思想.很多时候人们出于审美原因而禁用它,例如双击带有文本的标签时避免文本选择等.所以要么回答问题,要么提供一个实际的反点,并指明你所说的否定,不要不要只是以一般的方式抓住这个想法. (35认同)
  • @Omar:我很清楚这一点. (13认同)
  • 谢谢你.我正在处理一个拖动滑块,需要一种在此过程中不会选择文本的方法. (11认同)
  • @Bryce:就是不要.http://blog.slaks.net/2010/12/on-copy-prevention-in-html-part-2.html http://blog.slaks.net/2010/12/on-copy-prevention-in -html部分,3.html (2认同)

Dam*_*ien 101

如果你使用jQuery UI,有一个方法,但它只能处理鼠标选择(即CTRL+ A仍在工作):

$('.your-element').disableSelection(); // deprecated in jQuery UI 1.9
Run Code Online (Sandbox Code Playgroud)

如果您不想使用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; });
Run Code Online (Sandbox Code Playgroud)

  • 用jquery ui为第二个解决方案+1 (2认同)
  • 请注意,在jQuery UI 1.9中不推荐使用disableSelection() (2认同)

Ply*_*ynx 74

我发现这个答案(防止文本表的突出显示)最有帮助,也许它可以与另一种提供IE兼容性的方式相结合.

#yourTable
{
  -moz-user-select: none;
  -khtml-user-select: none;
  -webkit-user-select: none;
  user-select: none;
}
Run Code Online (Sandbox Code Playgroud)

  • 总是欣赏CSS的方式而不是一般使用jQuery或JS.就像jQuery动画和CSS过渡一样,浏览器内置的方式总是最好,最有效. (2认同)

小智 16

这是断路器选择的更全面的解决方案,以及一些热键的取消(例如Ctrl+ aCtrl+ c.测试: 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);
Run Code Online (Sandbox Code Playgroud)

并调用示例:

$(':not(input,select,textarea)').disableSelection();
Run Code Online (Sandbox Code Playgroud)

jsfiddle.net/JBxnQ/

这对于旧版本的FireFox来说也是不够的(我不知道哪个).如果所有这些都不起作用,请添加以下内容:

.on('mousedown', false)
Run Code Online (Sandbox Code Playgroud)

  • 为什么要两次调用`attr('unselectable','on')?这是一个错字还是有用的? (3认同)

小智 13

以下将禁用所有常见浏览器(IE,Chrome,Mozilla,Opera和Safari)中所有类'item'的选择:

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


小智 8

        $(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");
        });
Run Code Online (Sandbox Code Playgroud)


Cod*_*Spy 6

这可以使用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>
Run Code Online (Sandbox Code Playgroud)

调用此功能

<script type="text/javascript">
   disableSelection(document.body)
</script>
Run Code Online (Sandbox Code Playgroud)

  • 这个答案在2013年已经过时了 (3认同)

Zac*_*ham 6

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

$('body, html').mousedown(function(event) {
    event.preventDefault();
});
Run Code Online (Sandbox Code Playgroud)

所有这一切都是为了防止mousedown()bodyhtml标签中单击鼠标()时发生默认设置.你可以很容易只是通过改变文本之间的两个引号(如改变而改变的元素$('body, html'),以$('#myUnselectableDiv')使myUnselectableDivDIV是,好了,不可选.

一个快速的片段向您展示/证明:

$('#no-select').mousedown(function(event) {
  event.preventDefault();
});
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

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

取消一些热键(例如Ctrl+aCtrl+c.测试: Cmd+aCmd+c)

同样,通过使用上面弗拉基米尔的答案部分.(到这里发帖)