我的外部打印css是不适用,虽然我已经通过了在打印功能使用Jquery链接,请任何人能告诉我如何应用外部css

xqk2d5yq  于 2023-03-20  发布在  jQuery
关注(0)|答案(1)|浏览(94)

下面是我的html、CSS和JQuery代码,test.html和print.css都在同一个文件夹中测试

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://code.jquery.com/jquery-3.6.4.min.js" integrity="sha256-oP6HI9z1XaZNBrJURtCoUT5SUnxFr8s3BzRl+cbzUq8=" crossorigin="anonymous"></script>
    <title>Document</title>

    <script>
        $(document).ready(function(){
            $('#print').click(function () {
            var divContentss = $('#Display').html();
            var w = window.open();
            $(w.document.body).html(divContentss);
            w.document.write('<html><head><link rel="stylesheet" href="print.css"></head>');
            w.document.write('<body >');
            w.document.write(divContentss);
            w.document.write('</body></html>');
            console.log(w.document);
            w.print();
            w.close();
        });
        })
    </script>
</head>
<body>
    <button id="print">Print</button>
    <div id="Display">
        <h1 class="test">This is a test</h1>
    </div>

</body>
</html>
> Here is my print.css file

    .test{
        color:red;
        font-size:60px;
    }

我正在尝试使用外部打印css来调用单击打印按钮

lhcgjxsq

lhcgjxsq1#

我认为你的问题是css文件还没有时间加载,所以打印功能在它生效之前就进入了。
这段代码是你的一个副本,只是添加了一个超时。我已经给了它一秒钟,希望这是相当慷慨的-取决于您的服务环境,用户网络等,当然,至于什么最低限度,你可以摆脱是。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://code.jquery.com/jquery-3.6.4.min.js" integrity="sha256-oP6HI9z1XaZNBrJURtCoUT5SUnxFr8s3BzRl+cbzUq8=" crossorigin="anonymous"></script>
    <title>Document</title>

    <script>
        $(document).ready(function(){
            $('#print').click(function () {
            var divContentss = $('#Display').html();
            var w = window.open();
            $(w.document.body).html(divContentss);
            w.document.write('<html><head><link rel="stylesheet" href="print.css"><style>@include print.css; </style></head>');
            w.document.write('<body >');
            w.document.write(divContentss);
            w.document.write('</body></html>');
            console.log(w.document);
            setTimeout(
              function () {w.print();
                w.close();}, 1000)
        });
        })
    </script>
</head>
<body>
    <button id="print">Print</button>
    <div id="Display">
        <h1 class="test">This is a test</h1>
    </div>

</body>
</html>

相关问题