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();
// 樣式插入進去
// 打印識別不了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();
};
}