JavaScript打印功能没有携带样式表

时间:2017-01-01 04:32:17

标签: javascript html css

让我们从代码开始:

public function testGetElapsedTimeStringMethod()
{
    // Create Mock of the CarbonTimer class
    $mock = $this->getMockBuilder(CarbonTimer::class)
        ->getMock();

    // Configure the Mock Method
    $mock->method('getElapsedTime')
         ->willReturn(5);

    $this->assertEquals("5 seconds elapsed.", $mock->getElapsedTimeString());
}

代码非常适合这个输出

enter image description here

然后当我将css更改为这样的外部样式表时:

来自 var mywindow = window.open('', 'PRINT', 'height=600,width=800'); mywindow.document.write('<html><head><base href="/" /><title>' + document.title + '</title>'); mywindow.document.write('<style type="text/css" media="print" />table { width: 100%; }</style>'); mywindow.document.write('</head><body >'); mywindow.document.write('<h1> Returns for Today </h1>'); mywindow.document.write(document.getElementById(printableArea).innerHTML); mywindow.document.write('</body></html>'); mywindow.document.close(); // necessary for IE >= 10 mywindow.focus(); // necessary for IE >= 10*/ mywindow.print(); mywindow.close(); return true;

mywindow.document.write('<style type="text/css" media="print" />table { width: 100%; }</style>');

我得到一个空白的打印页面:

enter image description here

但如果我评论该行

mywindow.document.write('<link rel="stylesheet" href="assets/css/printstyles.css" type="text/css" />');

我明白了:

enter image description here

意思是,外部样式表正在运作。

外部样式表仅包含

//mywindow.print();
//mywindow.close();

知道它为什么不起作用?任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:2)

我在Chrome中遇到了同样的问题。我发现的问题是打印预览没有完全呈现,但页面仍然没有问题打印。

我最终做的是这样的:

var mywindow = window.open("", ...);
mywindow.document.write("...");
mywindow.document.close();
setTimeout(function() {
  mywindow.print();
  mywindow.close();
}, 10);
相关问题