将 div 和他的样式复制到新窗口

Era*_*eir 5 javascript css jquery

我正在尝试将 div 复制到新窗口进行打印,工作正常,但复制的 div 没有附加任何样式。

  $('#PrintNews').bind('click', function () {
        var printContents = new $("#divToPrint").clone();           
        var myWindow = window.open("", "popup", "width=1000,height=600,scrollbars=yes,resizable=yes," +
            "toolbar=no,directories=no,location=no,menubar=no,status=no,left=0,top=0");
        var doc = myWindow.document;
        doc.open();
        $(printContents).find("#PrintNews").remove();
        doc.write($(printContents).html());
        doc.document.close();
        doc.focus();
        doc.print();
        doc.close();
  });
 });
Run Code Online (Sandbox Code Playgroud)

我怎样才能在新窗口中打开该 div 进行打印,但又像原始 div 一样使用他的所有样式?

小智 5

你应该构建像这样的新窗口的 html,以链接外部 css 文件。

    doc.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">");
    doc.write("<html>");
    doc.write("<head>");
    doc.write("<link href='/css/print.css' rel='stylesheet' type='text/css' />"); // your css file comes here.
    doc.write("</head>");
    doc.write("<body>");
    doc.write($(printContents).html());
    doc.write("</body>");
    doc.write("</html>");
Run Code Online (Sandbox Code Playgroud)