【问题标题】:Make text not copyable HTML使文本不可复制 HTML
【发布时间】:2017-08-29 10:39:00
【问题描述】:

这不是上述问题的重复

我在我的网站上使用material-icons。为了添加一个图标,你必须做这样的事情:

<p class="material-icons">info_outline</p>

如果我现在复制该图标,它将复制文本“info_outline”。我知道你可以使用 user-select: none; 内部的 css 使元素无法选择,但这样做有问题。

以我的 sn-p 为例。如果我创建一个p 元素,其中有一个span,其中有user-select: none;,您将无法选择(并因此复制)跨度。但是,如果您复制整个p 元素,您仍然会得到span 的内容。我怎样才能防止这种情况发生?

span {
  user-select: none;
}

input {
  width: 100%;
}
<p>Copy this text with a <span>unselectable</span> piece of text... Or is it?</p>
<input type="text" placeholder="Past text here">

编辑: 由于很多人说这是与答案为user-select: none; 的问题重复的问题,请再看看我的问题。

我知道用户选择的工作原理!我知道您可以使元素无法选择。但是,如果你选择它周围的元素并复制它的内容,它会复制它的所有内容,甚至是带有user-select: none;的元素

【问题讨论】:

标签: css html


【解决方案1】:

首先使元素不可选择:

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

这已经在 Firefox 中有效。要让它在其他浏览器中运行,您必须使用 pseudo-elementsdata-attribute

像这样使用data-attribute

<span data-unselectable="unselectable content"></span>

现在我们可以在我们的伪元素::before::after的内容中添加这个文本:

span::before {
  content: attr(data-unselectable);
}

这是可行的,因为 dom 不会被 content 属性更新。

【讨论】:

    【解决方案2】:

    添加css样式

    .youClass {
        -webkit-touch-callout: none;
        -webkit-user-select: none;
        -khtml-user-select: none;
        -moz-user-select: none;
        -ms-user-select: none;
        user-select: none;
    }
    

    或者如果你想让它变得更好,可以使用类似这样的脚本。

    <script>
                window.onload = function() {
                    var labels = document.getElementsByTagName('label');
                    for (var i = 0; i < labels.length; i++) {
                        disableSelection(labels[i]);
                    }
                };
                function disableSelection(element) {
                    if (typeof element.onselectstart != 'undefined') {
                        element.onselectstart = function() { return false; };
                    } else if (typeof element.style.MozUserSelect != 'undefined') {
                        element.style.MozUserSelect = 'none';
                    } else {
                        element.onmousedown = function() { return false; };
                    }
                }
            </script>
    

    【讨论】:

    • 问题不在于使元素无法选择。问题是,如果我复制它周围的元素,它不应该复制不可选择元素的内容。在回答之前先看看我的问题。
    猜你喜欢
    • 1970-01-01
    • 2016-08-29
    • 2012-08-21
    • 2019-07-28
    • 2011-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多