首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用CSS打印DIV内容不起作用

使用CSS打印DIV内容不起作用
EN

Stack Overflow用户
提问于 2016-04-29 22:45:36
回答 4查看 5.5K关注 0票数 0

代码语言:javascript
复制
<script type="text/javascript">
    function PrintElem(elem) {
        Popup($(elem).html());
    }
    function Popup(data) {
        var mywindow = window.open('', 'mydiv', 'height=550,width=750');
        mywindow.document.write('<html><head><title></title>');
        mywindow.document.write('<link rel="stylesheet" href="~/Content/Site.css" type="text/css" media="print" />');
        mywindow.document.write('</head><body >');
        mywindow.document.write(data);
        mywindow.document.write('</body></html>');

        mywindow.document.close(); // necessary for IE >= 10
        mywindow.focus(); // necessary for IE >= 10

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

        return true;
    }
</script>

这是我打印DIV的Javascript,它工作得很好。但是我的CSS没有加载,我可以判断,因为我测试了粉红色,它仍然没有显示出来。请帮帮忙。HEre是我的CSS

代码语言:javascript
复制
@media print {
    .mydiv {
        background-color: white;
        height: 100%;
        width: 100%;
        position: fixed;
        top: 0;
        left: 0;
        margin: 0;
        padding: 15px;
        font-size: 14px;
        line-height: 18px;
        color:pink;
    }
}

EN

回答 4

Stack Overflow用户

发布于 2016-04-29 23:31:27

问题很可能是您的CSS试图引用窗口的名称,而不是窗口中的任何对象。因为我们不知道作为data发送的是什么,所以尝试这样做:

更改

代码语言:javascript
复制
mywindow.document.write(data);

代码语言:javascript
复制
mywindow.document.write("<div class='mydiv'>" + data + "</div>");
票数 1
EN

Stack Overflow用户

发布于 2016-04-29 23:17:44

我做了类似的(实际上是相同的)任务,如下所示:

打开"Print Version“文档(空模板),并在其onload事件中从其父目录中检索所需的div。

示例代码:

代码语言:javascript
复制
<!-- parent doc -->
<input type="button" value="Printer Version" onclick="doIt()" />
<div id="divPrint" style="display:none;">
   <iframe id="frPrint"></iframe>
</div>
<script>
function doIt(){
   document.getElementById('divPrint').style.display = '';
   document.getElementById('frPrint').src = "print.html?a=" + Math.random();//to avoid caching
}
function getContent(){
   return document.getElementsById('divData').innerHTML;
}
</script>

<!--print.html -->
...
<script type="text/javascript">
    window.onload = function () {
        var a = this.parent.getContent();
        document.body.innerHTML = a;
    }
    function printMe() {
        window.print();
    }
</script>
<style type="text/css">
    .right
    {
        float: right;
    }
</style>
<link href="/Styles/print.css" media="print" rel="stylesheet" />
...
票数 0
EN

Stack Overflow用户

发布于 2016-04-29 23:19:59

我在你的代码中看不到链接你的CSSHtml tag的类的引用,试着这样做:

代码语言:javascript
复制
mywindow.document.write('</head><body><div class="mydiv">');
mywindow.document.write(data);  
mywindow.document.write('</div></body></html>');

问候

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36941324

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档