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

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

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


当前回答

我看到很多详细的答案,但我认为写这个代码线应该足以完成所需的任务:

*{
    -webkit-user-select: none;
 }

其他回答

要得到我需要的结果,我发现我不得不使用:选择和用户选择

input.no-select:focus {
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}

input.no-select::selection {
    background: transparent;
}

input.no-select::-moz-selection {
    background: transparent;
}

在大多数浏览器中,可以通过使用用户选择的CSS属性的属性变量来实现这一点,最初提出,然后在CSS 3中被遗弃,现在在CSS UI级别4中提出。

*.unselectable {
   -moz-user-select: none;
   -khtml-user-select: none;
   -webkit-user-select: none;

   /*
     Introduced in Internet Explorer 10.
     See http://ie.microsoft.com/testdrive/HTML5/msUserSelect/
   */
   -ms-user-select: none;
   user-select: none;
}

在 Internet Explorer < 10 和 Opera < 15 中,您需要使用您想要不可选择的元素的不可选择属性。

<div id="foo" unselectable="on" class="unselectable">...</div>

不幸的是,这个属性没有继承,这意味着你必须在 <div> 中每个元素的起点标签中放置一个属性,如果这是一个问题,你可以使用JavaScript以重复为元素的后代:

function makeUnselectable(node) {
    if (node.nodeType == 1) {
        node.setAttribute("unselectable", "on");
    }
    var child = node.firstChild;
    while (child) {
        makeUnselectable(child);
        child = child.nextSibling;
    }
}

makeUnselectable(document.getElementById("foo"));


在某些浏览器(例如,Internet Explorer和Firefox)中,虽然不可能在未选择的元素中启动选项,但仍然不可能阻止在未选择的元素之前和之后开始的选项,而不会使整个文档不可选择。

对于 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  */
}

它很容易用:

-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.
}

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

您可以使用 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>