使文本不可选择且不可复制(webkit,由可复制文本包围)



下面的片段显示了如何使文本不可选择。遗憾的是,如果你在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生成的内容对于剪贴板(*)是不可见的这一事实,因此通过将文本移动到某个属性的空跨度,您可以获得与请求的剪贴板行为在视觉上相似的结果:

[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

如果可访问性/SEO不是一个问题,这可能是解决方案。在另一种情况下,它可能是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>

在样式属性中使用user-select: none;或在css文件中使用。

最新更新