[英]How can I programmatically copy all of the style attributes from one DOM element to another
[英]How to copy all CSS style from one DOM to another?
我使用此方法從我的 webapp 復制一個 DIV,以在新選項卡中打印或保存到數據庫,例如證書(這是一個自動過程,我不能要求用戶這樣做): https ://stackoverflow.com/a/40389924/1062933 [謝謝! ]
printForm(): void {
let printContents: any = document.getElementById('formTerms').innerHTML;
let w: any = window.open();
w.document.write(printContents);
w.document.write('<scr' + 'ipt type="text/javascript">' + 'window.onload = function() { window.print(); window.close(); };' + '</sc' + 'ript>');
w.document.close(); // necessary for IE >= 10
w.focus(); // necessary for IE >= 10
}
但是生成的 HTML 沒有在主選項卡中具有的 CSS 未格式化。
有沒有辦法也復制該 DIV 中使用的 CSS styles?
我正在使用 Angular4 和 Teradata Covalent
如果您知道哪些<style>
標簽被用於設置div
的樣式,您可以將這些內容復制到新的 window 中的新樣式標簽中。但是,這不會直接在div
本身上包含 styles。
白一點手動, getComputedStyle function 可以給出元素的當前樣式,然后您可以在新的 window 中應用它。如果您要復制的div
中有子項,則必須遞歸地執行此操作或將常見的 styles 解析為生成的樣式表。
鏈接頁面中有示例,但我將在此處復制:
// print one or all of the style properties on the element
function dumpComputedStyles(elem,prop) {
var cs = window.getComputedStyle(elem,null);
if (prop) {
console.log(prop+" : "+cs.getPropertyValue(prop));
return;
}
var len = cs.length;
for (var i=0;i<len;i++) {
var style = cs[i];
console.log(style+" : "+cs.getPropertyValue(style));
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.