简体   繁体   English

如何在不丢失样式的情况下复制文本?

[英]How to copy text without losing it's style?

The general text copy thing just copies the text without giving nay importance to the styles.一般的文本复制东西只是复制文本而不重视styles。 Is there any way to copy text without losing it's inherent properties like font family, font size etc. A javascript function would be helpful.有什么方法可以复制文本而不丢失其固有属性,如字体系列、字体大小等。 javascript function 会有所帮助。 Thanks.谢谢。

Having the right element selected on the HTML DOM tree, right-click on it and choose “Copy” > “Copy styles”.在 HTML DOM 树上选择正确的元素,右键单击它并选择“复制”>“复制样式”。

Source: https://getcssscan.com/blog/how-to-inspect-copy-element-css来源: https://getcssscan.com/blog/how-to-inspect-copy-element-css

You can use Clipboard.write() with both text and html parts:您可以将Clipboard.write()与文本和 html 部件一起使用:

TS Playground TS游乐场

// This will return the raw HTML, but perhaps you want to do something different,
// for example: recursively embed computed styles:
// https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle
function serializeElement (element: Element): string {
  return element.outerHTML;
}

async function copyTextWithStyles (element: Element): Promise<void> {
  const html = serializeElement(element);
  const htmlBlob = new Blob([html], {type: 'text/html'});

  const text = element.textContent ?? '';
  const textBlob = new Blob([text], {type: 'text/plain'});

  const clipboardItem = new ClipboardItem({
      [htmlBlob.type]: htmlBlob,
      [textBlob.type]: textBlob,
  });

  return navigator.clipboard.write([clipboardItem]);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM