复制透明背景文本

问题描述 投票:0回答:1

解释我的问题的最简单方法是使用 Youtube 网站来复制它。我正在 Mac OS 上使用 Google Chrome 98 进行测试:

重现步骤:

  1. 以深色模式访问 Youtube(背景为#181818)(在深色模式下最容易看到效果,但它也应该在浅色模式下工作,但背景将为#f9f9f9)

  2. 打开开发者工具并将以下内容粘贴到控制台中:

const div = document.createElement("div");
div.style.position = "absolute";
div.style.left = "100px";
div.style.top = "300px";
div.innerText = "This is a test";
div.style.setProperty("background-color", "transparent", "important");
document.body.appendChild(div);
  1. 尝试复制文本并粘贴到 Google 文档中。看到黑色背景。

我的目标是通过JavaScript插入一个div,这样复制粘贴文本时就不会出现黑色背景。我怀疑,由于我在复制时将背景设置为透明,因此它继承了页面的背景(因为 Youtube 在其脚本标签之一中设置了

html { background: #181818 !important}

因此,如果我尝试这样做:

div.style.setProperty("background-color", "rgba(0,0,0,0.01)", "important");
,而不是使背景透明,黑色背景似乎消失了(即使它在技术上仍然存在)。在这种情况下,有什么方法可以使插入的 div 的文本在粘贴时真正透明吗?

我确实想保留除背景之外的所有其他文本格式,因此从 JavaScript 拦截副本并不理想,我正在寻找 CSS 解决方案。

javascript html css google-chrome copy-paste
1个回答
0
投票

我正在研究类似的问题,并发现使用 pre 而不是 div 是一种解决方法。

body {
  background-color: yellow;
  font-family: Times, "Times New Roman", Georgia, serif;
}

pre {
  font-family: Times, "Times New Roman", Georgia, serif;
}
<div>I want to copy text in <strong>div</strong> with styles such as <b>bold</b>, <i>italic</i>, <u>underline</u>, etc., except for the background color.</div>

<pre>I want to copy text in <strong>pre</strong> with styles such as <b>bold</b>, <i>italic</i>, <u>underline</u>, etc., except for the background color.</pre>

我不知道为什么会这样。

令人惊讶的是,复制上面代码片段中 div 中的部分文本包括背景颜色,而选择并复制 div 中的整个文本不包括背景颜色。 选区接触 pre 时是否不再包含背景颜色?

这可能是 Chromium 特有的行为。 (我还没有在 Safari 或 Firefox 中测试过这一点。) 我希望得到对此有更多了解的人的解释。

希望这有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.