javascript - 如何使用 Javascript 将 CSS 添加到新窗口?

标签 javascript html css printing

我使用此代码获取 html 元素以便打印出我的表格。

<script type="text/javascript">


    function printPage(){
            var width = screen.width - 50;
            var tableData = '<table width="'+width+'" border="1">'+document.getElementsByTagName('table')[0].innerHTML+'</table>';
            var data = '<button onclick="window.print()">Print this page</button>'+tableData;     
            myWindow=window.open('','','width=auto,height=auto');
            myWindow.innerWidth = screen.width;
            myWindow.innerHeight = screen.height;
            myWindow.screenX = 0;
            myWindow.screenY = 0;
            myWindow.document.write(data);
            myWindow.focus();
        };
</script>

但是,我有一个问题。

我的 CSS 样式没有出现在打印预览中。

我应该怎么做才能在我的 HTML 代码中获取我的 CSS 元素?注意:我的 CSS 样式使用类来获取样式值。

最佳答案

尝试添加指向您的 css 文件的链接。

function printPage(){
        var width = screen.width - 50;
        var tableData = '<table width="'+width+'" border="1">'+document.getElementsByTagName('table')[0].innerHTML+'</table>';

        var cssHead = '<head><link rel="stylesheet" type="text/css" href="mystyle.css"></head>'

        var data = cssHead + '<button onclick="window.print()">Print this page</button>'+tableData;     
        myWindow=window.open('','','width=auto,height=auto');
        myWindow.innerWidth = screen.width;
        myWindow.innerHeight = screen.height;
        myWindow.screenX = 0;
        myWindow.screenY = 0;
        myWindow.document.write(data);
        myWindow.focus();
    };

关于javascript - 如何使用 Javascript 将 CSS 添加到新窗口?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22657146/

相关文章:

javascript - JS - 将字符串映射到对象数组 ¿如何更改键名?

javascript 真假

javascript - 提交表单时(验证之前)立即显示模式

javascript - 使用 JavaScript 下载不带扩展名的文件

javascript - 按下按钮时,如何使此交通灯序列重复多次>

javascript - 滚动后修复导航栏并平滑滚动下方的内容

html - 在不同的行上显示 radio 输入,但将文本与 radio 选择器保持在同一行

javascript - 比较大于 1000 的数字时奇怪的 JavaScript 行为

javascript - 简单 HTML 表单创建循环中的永恒循环

HTML/CSS 菜单悬停链接