html从剪贴板副本中排除文本

gsf*_*gsf 6 html css clipboard

我在另一个范围内有一个跨度.我想允许用户能够从父跨度中选择文本,而不是从子跨度中选择文本.

注意:( user-select家庭)不起作用.它阻止选择在此区域中开始或结束,但如果我使用父跨度中的文本中的选择将其包围,则文本仍在最终剪贴板结果中.

例如:

<head>
<style>
  .hole-hint {
    display: inline-block;
    position: absolute;
    bottom: 45%;
    font-size: 12px;
    color:rgb(255, 0, 0);
    background-color:rgba(255, 225, 225, 0.5);
    z-index:1;
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    -o-user-select: none;
    user-select: none;
  }
  .hole {
    padding-top: 7px;
    position: relative;
    background-color:#EEEEEE;
  }
  </style>
  </head>
  <body>
      <span> this is the parent text<span class="hole"><span class="hole-hint">no copy</span></span>and this is text on the other side   </span>
  </body>
  </html>
Run Code Online (Sandbox Code Playgroud)

xer*_*r21 2

我有类似的需求,我使用占位符来表示尚未输入的文本。但是,如果用户想要复制该文本块,他们永远不会希望复制的文本中包含占位符。我想出了以下解决方案。

这是一个例子,它使用了一些 jquery 但可以替换

CSS(并不是真的需要只是为了好玩)

div.copying { background-color: yellow; }
div.copying .nocopy { display: none; }
Run Code Online (Sandbox Code Playgroud)

HTML(注:如果要应用到整个页面,请将 oncopy 移至 )

<body>
  <div>text not related to the copy, dont select this</div>
  <div oncopy="handleHideCopy(this);" class="container">
    <span>the text between &gt;<span class="nocopy"> I don't want this text copied </span><span>&lt; will be excluded from copy, or at least in IE</span>
  </div>
  <div>and don't select this either</div>
</body>
Run Code Online (Sandbox Code Playgroud)

JS

function handleHideCopy(el) 
{
    $(el).addClass('copying');
    var innerHtml = el.innerHTML;
    $(el).find('.nocopy').remove();
    setTimeout(function(){
        $(el).removeClass('copying');
        $(el).children().remove();
        el.innerHTML = innerHtml;
    },300);
}
Run Code Online (Sandbox Code Playgroud)

这样做的原因是因为 oncopy 在复制发生之前在父元素上调用,并且必须隐藏的内容实际上必须被删除,因为 display:none 对于复制绝对没有任何作用。

不应使用innerHTML 处理大量的html,而应使用更有针对性的DOM 删除/插入来删除内容并将其放回其所属位置。我没有方便的例子。