JavaScript 所见即所得范围打印
发布于: | 没有评论 | 分类:JavaScript
JavaScript
const setStyle = function (element, style) {
for (let i = 0; i < style.length; i++) {
const key = style[i]
element.style[key] = style[key]
}
}
const copyStylesToClone = function (elA, elB) {
const style = window.getComputedStyle(elA, null)
setStyle(elB, style)
for (let i = 0; i < elA.children.length; i++) {
copyStylesToClone(elA.children[i], elB.children[i])
}
}
const convertStyleObjectToString = function (style) {
const el = document.createElement('div')
for (const key in style) {
el.style[key] = style[key]
}
return el.style.cssText
}
const convertStyleSheetToString = function (style) {
let str = ''
for (const key in style) {
str += ''.concat(key, '{').concat(convertStyleObjectToString(style[key]), '}')
}
return str
}
export const printAsSeen = function (element, config) {
if (!config) {
config = {}
}
const data = element.cloneNode(true)
copyStylesToClone(element, data)
const iframe = document.createElement('iframe')
iframe.style.display = 'none'
document.body.after(iframe)
const iframeInnerDocument = iframe.contentDocument
const iframeInnerWindow = iframe.contentWindow
const iframeInnerStyle = document.createElement('style')
iframeInnerStyle.innerHTML += convertStyleSheetToString(config.style)
iframeInnerDocument.body.append(data)
iframeInnerDocument.head.append(iframeInnerStyle)
iframeInnerWindow.print()
setTimeout(function () {
return iframe.remove()
}, 10000)
}
标签:
订阅评论
登录
0 评论