【问题标题】:How to copy text without losing it's style?如何在不丢失样式的情况下复制文本?
【发布时间】:2022-01-26 00:16:31
【问题描述】:

一般的文本复制只是复制文本而不重视样式。有什么方法可以复制文本而不丢失其固有属性,如字体系列、字体大小等。javascript 函数会很有帮助。谢谢。

【问题讨论】:

    标签: javascript html css


    【解决方案1】:

    在 HTML DOM 树上选择正确的元素,右键单击它并选择“复制”>“复制样式”。

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

    【讨论】:

      【解决方案2】:

      您可以将 Clipboard.write() 用于文本和 html 部分:

      TS Playground

      // 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]);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-11-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-10-30
        • 2020-09-10
        相关资源
        最近更新 更多