P粉3065239692023-08-18 12:19:00
Okay, I have an answer. I should know better as I just finished teaching a similar topic.
The code is valid, but it runs too early. I need to wait for the document to finish loading.
This is a working version:
var iframe = document.createElement('iframe'); var div = document.querySelector('div#sidebar'); var content = div.innerHTML; iframe.srcdoc = `<!DOCTYPE html><html><head></head><body>${content}</body></html>`; document.body.append(iframe); // 等待iframe加载完成: iframe.onload = () => { iframe.contentWindow.print(); iframe.contentWindow.addEventListener('afterprint', event => { iframe.remove(); }); };