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

时间:2014-03-26 09:51:02

标签: 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样式使用类来获取样式值。

1 个答案:

答案 0 :(得分:4)

尝试添加指向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();
    };