代码之家  ›  专栏  ›  技术社区  ›  Edgar Navasardyan

用于打印的CSS不应用于动态生成的HTML

css
  •  0
  • Edgar Navasardyan  · 技术社区  · 7 年前

    我正在尝试打印一个来自服务器端的HTML。我现在面临的主要问题是css由于某种原因没有被应用。看小提琴。我做错什么了吗?

    另外,带边框的JS用于在同一选项卡中打开打印窗口。以前我遇到过这样的麻烦:当新标签打开时,原来标签上的JS停止工作,直到我关闭了第二个带有打印内容的标签

    https://jsfiddle.net/7L9onps1/

    @media print {
      body * {
        visibility: hidden;
      }
     .test {
       visibility: visible;
        position: absolute;
        left: 0;
        top: 0;
        background: red;
        color: red;
        -webkit-print-color-adjust: exact; 
      }
    }
    

    JS公司:

    document.querySelector("#print").addEventListener("click", function() {
         var html = '<div class="test">Test</div>';
         print(html);
    });
    
    function print(html) {
        // https://www.sitepoint.com/5-jquery-print-page-options/
        document.innerHTML = html;
        $('<iframe>', {
            name: 'myiframe',
            class: 'printFrame'
        }).appendTo('body').contents().find('body').append(html);
    
        window.frames['myiframe'].focus();
        window.frames['myiframe'].print();
        setTimeout(() => { $(".printFrame").remove(); }, 1000);
    }
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   Alexander Menger    7 年前

    我用图书馆来做这件事: https://github.com/DoersGuild/jQuery.print