//这里是获取我需要打印的dom 元素
let wpt = document.getElementById('myDiv');
let newContent = wpt.innerHTML;
//创建iframe
const iframeEl = document.createElement("iframe");
iframeEl.class = "iframe";
//将元素放置最底层,防止其覆盖了其他元素
iframeEl.style.position = "fixed";
iframeEl.style.zIndex = -99;
//添加到页面
document.querySelector("body").append(iframeEl);
const documentEl = iframeEl.contentDocument;
//把打印dom元素赋值给iframe
documentEl.body.innerHTML = newContent;
iframeEl.contentWindow.print()
注意:需打印内容需要使用行内样式,不然打印时样式无效
原文地址:https://blog.csdn.net/weixin_49066399/article/details/135437882