对于像按钮一样运作的插槽(例如,这个 Stack Overflow 页面侧栏上的按钮题为 问题、标签和用户)或选项卡,如果用户随机选择文本,则是否有 CSS 标准方式禁用突出效果?

我意识到可以用JavaScript做到这一点,而谷歌有点带来了Mozilla-only -moz-user-select选项。

有没有一个符合标准的方式来实现这一点与CSS,如果没有,什么是“最好的实践”方法?


当前回答

你尝试过吗?

.disableSelect{
    user-select: none;
    -webkit-user-select: none;
    -ms-user-select: none;
    -webkit-touch-callout: none;
    -o-user-select: none;
    -moz-user-select: none;

    pointer-events:none;
}

其他回答

对于 Internet Explorer 此外,您还需要添加 pseudo class focus (.ClassName:focus) 和 outline-style: none。

.ClassName,
.ClassName:focus {
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
    outline-style: none; /* Internet Explorer  */
}

我喜欢Hybrid CSS + jQuery 解决方案。

要使 <div class="draggable"></div> 中的所有元素不可选择,请使用此 CSS:

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

.draggable input {
    -webkit-user-select: text;
     -khtml-user-select: text;
       -moz-user-select: text;
         -o-user-select: text;
            user-select: text;
 }

然后,如果您正在使用 jQuery,请将其添加到 $(文件)。ready() 区块中:

if (($.browser.msie && $.browser.version < 10) || $.browser.opera) $('.draggable').find(':not(input)').attr('unselectable', 'on');

我猜你仍然想要任何输入元素是互动的,因此 :not() pseudo-selector. 你可以使用“*”而不是如果你不在乎。

Caveat: Internet Explorer 9 可能不需要此额外的 jQuery 件,所以您可能想在那里添加一个版本检查。

我将各种浏览器 CSS 选择属性与 Internet Explorer < 9 所需的不可选择标签相结合。

<style>
[unselectable="on"] {
    -webkit-user-select: none; /* Safari */
    -moz-user-select: none; /* Firefox */
    -ms-user-select: none; /* Internet Explorer 10+/Edge */
    user-select: none; /* Standard */
}
</style>
<div unselectable="on">Unselectable Text</div>

您可以通过 : 之前使用此解决方案:

天天天天天天天天天天天天天天天天天天天天天天天天天天天天天天天天天天天天天天天天天天天天天天天天天天天天天天天天天天天天天天天天天天天天天

JsFiddle - https://jsfiddle.net/grinmax_/9L1cckxu/

快速黑客更新

如果您使用所有 CSS 用户选择的属性(包括浏览器预定),则仍然存在一个问题。

.div {
    -webkit-user-select: none; /* Chrome all / Safari all */
    -moz-user-select: none;    /* Firefox all             */
    -ms-user-select: none;     /* Internet Explorer  10+  */
     user-select: none;        /* Likely future           */
}

正如CSS-Tricks所说,问题是:

WebKit 仍然允许文本复制,如果您选择周围的元素。

您也可以使用下面的一个,以确保一个完整的元素被选中,这意味着如果您点击一个元素,所有包含在该元素的文本将被选中。

.force-select {
    -webkit-user-select: all;  /* Chrome 49+     */
    -moz-user-select: all;     /* Firefox 43+    */
    -ms-user-select: all;      /* No support yet */
    user-select: all;          /* Likely future  */
}