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

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

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


当前回答

对于 Internet Explorer 的 JavaScript 解决方案是:

onselectstart="return false;"

其他回答

我喜欢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 件,所以您可能想在那里添加一个版本检查。

更好的是,您可以禁用文本选择。

如果你喜欢Sass(SCSS),而你不想使用Compass,你可以这样做:

风格.scss

@mixin user-select($select) {
    -webkit-touch-callout:#{$select};
    @each $pre in -webkit-, -moz-, -ms-, -o-, -khtml- {
        #{$pre + user-select}: #{$select};
    }
    #{user-select}: #{$select};
}

.no-select {
    @include user-select(none);
}

你可以在Firefox和Safari(Chrome也?)中做到这一点。

::selection { background: transparent; }
::-moz-selection { background: transparent; }

您可以使用 CSS 或 JavaScript。

JavaScript 模式支持较旧的浏览器,如旧版本的 Internet Explorer 也,但如果不是你的情况,使用 CSS 模式,然后:

HTML 和 JavaScript:

<html onselectstart='return false;'> <body> <h1> 这是标题!</h1> <p> 我是文本,如果你选择我,我不会被选中。

HTML / CSS:

.not-selectable { -webkit-touch-callout: none; -webkit-user-select: none; -khtml-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } <body class="not-selectable"> <h1>This is the Heading!</h1> <p>And I'm the text, I won't be selected if you select me.</p> </body>

它很容易用:

-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
-o-user-select: none;
user-select: none;

替代:

假设你有一个 <h1 id="example">Hello, World!</h1>. 你将不得不删除内部HTML的 h1,在这种情况下Hello, World. 然后你将不得不去CSS并这样做:

#example::before // You can of course use **::after** as well.
{
    content: 'Hello, World!'; // Both single-quotes and double-quotes can be used here.

    display: block; // To make sure it works fine in every browser.
}

现在它只是认为它是一个区块元素,而不是文本。