最近碰到一個需求:將彈窗中的表單打印出來,還要保留彈窗表單的樣式,為了對頁面造成的影響最小采取iframe方案。
獲取彈窗html內(nèi)容很好辦
const print = () => {
const printBox = document.querySelector(".problem-wrapper");
const iframe = document.createElement("iframe");
iframe.style.display = 'none'
iframe.name = "printIframe";
document.body.appendChild(iframe);
//將彈窗html代碼給iframe
iframe.contentDocument!.body.innerHTML = printBox!.innerHTML;
iframe.contentWindow?.print();
setTimeout(() => {
document.body.removeChild(iframe);
}, 5000);
}
這個時候我們點擊打印按鈕調(diào)用上面的方法,會發(fā)現(xiàn)表單缺少樣式,怎么拿到缺少的css樣式呢,代碼如下
const stylesText = Array.from(document.styleSheets)
.map((s) =>
Array.from(s.cssRules)
.map((z) => z.cssText || "")
.join("\n")
)
.join("\n");
將代碼加入方法print方法中
最終方法成品:文章來源:http://www.zghlxwxcb.cn/news/detail-698165.html
const print = () => {
const stylesText = Array.from(document.styleSheets)
.map((s) =>
Array.from(s.cssRules)
.map((z) => z.cssText || "")
.join("\n")
)
.join("\n");
//需要打印的容器的類名
const printBox = document.querySelector(".problem-wrapper");
const iframe = document.createElement("iframe");
iframe.style.display = "none";
iframe.name = "printIframe";
document.body.appendChild(iframe);
iframe.contentDocument!.head.innerHTML = `<style>${stylesText}</style>`;
iframe.contentDocument!.body.innerHTML = printBox!.innerHTML;
iframe.contentWindow?.print();
setTimeout(() => {
document.body.removeChild(iframe);
}, 5000);
};
補充:如果有哪些不需要打印的部分可以在上加上一個類名,并且在css部分寫一一個媒體查詢。
vue中演示:
標(biāo)簽:<div class="noPrint">不需要打印的部分</div>
樣式:<style> @media print {.noPrint {display: none;}}</style>
文章來源地址http://www.zghlxwxcb.cn/news/detail-698165.html
到了這里,關(guān)于vue、js獲取頁面中所有css樣式(包括link標(biāo)簽)案例為打印使用的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!