vue 打印局部dom 支持样式 iframe 打印 解决图片丢失问题
直接撸代码
print(){
var el = document.getElementsByClassName("detail-content");
console.log(el);
var iframe = document.createElement('IFRAME');
var doc = null;
iframe.setAttribute('style', 'position:absolute;width:0px;height:0px;left:-500px;top:-500px;');
document.body.appendChild(iframe);
doc = iframe.contentWindow.document;
doc.write('<div class="detail-content content_wrap pl30">' + el[0].innerHTML + '</div>');
doc.close();
// body{display:table} 加进去,否则会多出空白页
// 样式插入进去
// 打印识别不了background-color 要再background-color 下添加 -webkit-print-color-adjust: exact;
var cssString =`.content_wrapxxx 这是你的局部dom 的样式`;
var style=iframe.contentWindow.document.createElement("style");
style.setAttribute("type", "text/css");
if(style.styleSheet){// IE
style.styleSheet.cssText = cssString;
} else {// w3c
var cssText = iframe.contentWindow.document.createTextNode(cssString);
style.appendChild(cssText);
}
var heads = iframe.contentWindow.document.getElementsByTagName("head");
if(heads.length) {
heads[0].appendChild(style);
}else{
iframe.contentWindow.document.documentElement.appendChild(style);
}
iframe.contentWindow.focus();
console.log(iframe);
iframe.onload = function(){ //解决图片显示不了的问题
iframe.contentWindow.print();
};
}