宜搭在线js上点击按钮实现打印div效果

export function onClick() {
console.log('onClick');
const outerContainer = document.querySelector(".labelcode-tag-container");
if (!outerContainer) {
this.utils.toast({
title: '请先展开二维码标签',
type: 'error',
});
return;
}
const shadowRoot = outerContainer.shadowRoot
if (!shadowRoot) {
this.utils.toast({
title: '无妨访问shadow DOM',
type: 'error',
});
return;
}
const printContainer = shadowRoot.querySelector('#sheet-container');
// const printContainer = shadowRoot.querySelector('.tag-container');
if (!outerContainer) {
this.utils.toast({
title: '未找到待打印区域',
type: 'error',
});
return;
}
// 打印指定区域
printElement(printContainer);
}
//打印指定DOM元素
function printElement(element) {
// 创建打印 iframe(避免影响原页面样式)
const iframe = document.createElement('iframe');
iframe.style.position = 'absolute';
iframe.style.top = '-9999px';
iframe.style.left = '-9999px';
iframe.style.width = '100%';
iframe.style.height = '100%';
iframe.style.zIndex = '9999';
document.body.appendChild(iframe);

// 复制待打印元素到iframe
const iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
// 复制原元素的所有内容(包括子节点)
// iframeDoc.body.appendChild(element.cloneNode(true));
iframeDoc.open();
// 直接在 iframe 的 中写样式
iframeDoc.write(`



打印预览




${element.innerHTML}


`);
iframeDoc.close();

// 打印完成后移除iframe
setTimeout(() => {
iframe.contentWindow.focus();
iframe.contentWindow.print();

setTimeout(() => {
document.body.removeChild(iframe);
}, 300);
}, 500);
}

posted @ 2025-11-21 15:04  不完美的完美  阅读(24)  评论(0)    收藏  举报