js的window.print()功能 有些背景色设置和背景图片无法显示的问题
写在前面:需求需要调用浏览器原生的print功能;下载保存为pdf,出现了 部分样式消失的情况
方法一:(此方法实测,针对我出现的情况,可用)
//打印机媒体查询
@media print {
body{
-webkit-print-color-adjust:exact;
-moz-print-color-adjust:exact;
-ms-print-color-adjust:exact;
print-color-adjust:exact;
}
button{display:none;}
}
方法二:(此方法,是CSDN上的同行看到的,未测试,估计可用,小伙伴可以试试!)
function printPage(){
var office = document.getElementsByClassName('office')[0];
var imgs = office.getElementsByTagName('img');
var img,src;
if(!imgs.length){
src = window.getComputedStyle(office,null).getPropertyValue('background-image').replace(/(^url)|\(|\)|\"/g,'');
img = document.createElement('img');
img.src=src;
img.height = 150;
img.width = 150;
office.style.backgroundImage = 'none';
office.appendChild(img);
}
window.print();
//取消打印还原
setTimeout(function(){
office.removeChild(img);
office.style.backgroundImage = 'url("'+ src +'")';
},100)
}
-end-