我使用此代码获取 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/