javascript - 使用 CSS 打印 DIV 内容,不起作用

标签 javascript jquery html css printing

<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>

这是我的 Javascript,它可以打印 DIV,并且运行良好。但是我的 CSS 没有加载,我知道是因为我测试了粉红色,但它仍然没有显示出来。请帮忙。这是我的 CSS

@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;
    }
}

最佳答案

问题很可能是因为您的 CSS 试图引用 WINDOW 的名称,而不是 WINDOW 中的任何对象。因为我们不知道作为数据发送的是什么,试试这个:

改变

mywindow.document.write(data);

mywindow.document.write("<div class='mydiv'>" + data + "</div>");

关于javascript - 使用 CSS 打印 DIV 内容,不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36941324/

相关文章:

javascript - 通过 NodeJS 将消息发布到 Firebase Cloud Messaging

JQuery 代码不工作。我究竟做错了什么?回调、变量作用域、链接?

jquery - 在 jQuery 中默认折叠 SlideToggle() 元素

html - 如何在用户单击时设置对象样式

javascript - 在 Google Chrome 中捕获下载

javascript - 更改网页上的光标颜色?

javascript - 如何开始旋转一个 bootstrap Font Awesome 图标,然后使用 jQuery 让它停止

html - 重定向到 html href url(li a 标签)不起作用,样式问题?

html - 动态 LI 显示顺序

javascript - 显示/隐藏 div 取决于 viewpwort 中的特定类