以下代码片段展示了如何使文本不可选择。遗憾的是,如果您在 Chrome 中选择任意一侧的文本,则当您复制并粘贴时,未选择的文本也会被粘贴。
有没有什么办法,可以把大量的文字,通篇都是不可选择的内容,复制粘贴,并且不可以选择的内容都不粘贴?
.hide {
color: orange;
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
<div>Hello this text is selectable <span class="hide">but I'm not</span> You can select me all day!</div>
http://codepen.io/regan-ryan/pen/XdodGx
编辑:这个问题看起来确实可能是重复的,因为关于这个主题已经有大约 12 个问题了。然而,经过广泛的搜索后,我找不到我的特定问题,所以我认为它值得拥有一个更具体的问题标题。
更多解决方法:您可以利用 CSS 生成的内容对于剪贴板 (*) 不可见的事实,因此,将文本移动到某个属性的空跨度,您将获得与请求的 clibpoard 行为在视觉上相似的结果:
[data-text] {
color: orange;
}
[data-text]::after {
content: attr(data-text);
}
<div>Hello this text is selectable <span data-text="but I'm not"></span> You can select me all day!</div>
http://codepen.io/myf/pen/jqXrNZ
如果可访问性/搜索引擎优化不是问题,这可能是解决方案。在其他情况下,它可能是 HTML 中的真实文本,但通过“按需”脚本移动到属性。
(*) 更新:如评论中所述( 如何使用CSS禁用文本选择突出显示?)Internet Explorer实际上涉及CSS在剪贴板中生成的内容。啊啊。
css 可以禁用选择突出显示,但如果你想不复制文本,请使用这一小段 jquery 代码
$('.hide').on('copy paste cut drag drop', function (e) {
e.preventDefault();
});
$('.hide').on('copy paste cut drag drop', function (e) {
e.preventDefault();
});
.hide {
color: orange;
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Hello this text is selectable <span class="hide">but I'm not</span> You can select me all day!</div>
您可以尝试使用
window.getSelection
阅读突出显示的文本。请尝试以下代码示例并查看控制台。这样,您可以从字符串中删除不需要的文本并将其复制到剪贴板。但这并不简单,甚至可能不可能。这只是一个想法。
function getSelectedText() {
console.log(window.getSelection());
}
document.onmouseup = getSelectedText;
document.onkeyup = getSelectedText;
.hide {
color: orange;
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
}
<!-- begin snippet: js hide: false -->
<div>Hello this text is selectable <span class="hide" unselectable="on">but I'm not</span> You can select me all day!</div>
在 style 属性中使用
user-select: none;
或在 css 文件中使用。
前面的答案很好,但我想详细说明一个可能的解决方案,以更严格地定义不可复制。
如果我们定义“不可复制”意味着它不能通过以下方式复制:
例如:您向用户提供多个安全令牌,您希望防止这些令牌被记录、在剪贴板中的停留时间超过预期、被扩展程序读取等。
那么纯 CSS 方法无法满足要求,因为您最终需要将数据写入可通过代码访问或使用页面上的 javascript 查询的位置。
如果我们将“复制”排除在外,例如使用 OCR 之类的工具解析页面的视觉效果,查询页面或元素中的像素,或者主动操作页面(写入页面),然后这样的操作就可以工作:
画布看起来就像 DOM 中的文本,但在不破坏加密的情况下不能进行文本复制或拦截。
在您还担心可能能够写入文档的恶意干扰的情况下 - 您可以编写一个扩展程序,该扩展程序可以获取私钥包装的有效负载并在扩展程序中解密+显示它,或者传递纯像素返回并在页面上有一个脚本,可以将其提交到 DOM。
当然,值得注意的是,写入 DOM 的任何像素都可以被页面上的其他内容读取,这就是为什么在扩展中显示它是我们研究中“最安全”的解决方案 - 但并没有这样做像所要求的问题那样内联。