【问题标题】:How can I stop text from being selected?如何阻止文本被选中?
【发布时间】:2011-03-29 01:08:18
【问题描述】:

在我的网络应用中,用户有时可以多次单击同一个按钮,跳过消息和内容,从而选择</a>

那么如何使用 Javascript (jQuery) 防止这种情况发生

【问题讨论】:

  • 它会阻止他们继续浏览消息吗?如果不是,那么我建议不要这样做,因为它可能还会阻止他们想要选择文本。
  • 在我看来这不会影响他们的导航能力——只是不小心选择了。 Marek 在下面的答案中包含的链接仅允许在某些元素上禁用文本选择。大概 Ben 只会禁用对杀死他的用户的一个 标签的选择。

标签: javascript jquery cross-browser textselection


【解决方案1】:

这个解决方案对我有用: http://chris-barr.com/entry/disable_text_selection_with_jquery/

$(function(){
    $.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;});
            }
        });
    });
    $('.noSelect').disableTextSelect();//No text selection on elements with a class of 'noSelect'
});

【讨论】:

  • 该网址似乎已移至:chris-barr.com/index.php/entry/…
  • 链接中的示例不适用于最新版本的 Jquery。 $.browser 不再存在。
  • 对于那些遇到这个答案的人来说,Blowsie 描述的 CSS 方法是一个更好的解决方案(并且与链接的 jQuery 答案一样)。
【解决方案2】:

你不需要脚本,这里是css:

-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;

【讨论】:

  • 问这个问题的人可能已经预先决定要使用 JS,但您的回答比任何脚本都要好得多。 +1
  • 适用于 Chrome 25,但不适用于 IE10。 Ctrl+A 选择页面上的所有文本。如果我双击文本,它会停止选择文本,但是如果我从不使用此 CSS 的区域拖动到使用此 CSS 的区域,它仍然会突出显示文本。
猜你喜欢
  • 2017-01-01
  • 2015-01-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-11
  • 1970-01-01
  • 1970-01-01
  • 2021-09-15
相关资源
最近更新 更多