繁体   English   中英

div 元素的 Svelte 打印内容

[英]Svelte print contents of a div element

嗨,我正在为我正在做的一个副项目使用 svelte,我想打印一张收据而不是整个页面。 有办法吗? 我看到其他一些帖子谈论如何使用普通 JavaScript 打印 div 元素,但这在 svelte 中不起作用。

示例代码我只想打印具有 class 可打印元素

<div class="printable">
    <h1>hello world</h1>
</div>

<div class="navbar">
    <a href="/">home</a>
    <a href="/next">next</a>
    <a href="/profile">profile</a>
</div>

您可以使用@media查询或使用事件( beforeprint / afterprint )和本地状态来显示/隐藏事物。

在定位元素方面,如果您在打印时反转逻辑并标记要删除的元素,则更容易。 隐藏所有没有类的元素很容易,但默认情况下会在可打印元素中包含h1

例如:

<div>
    <h1>hello world</h1>
</div>

<div class="navbar not-printable">
    <a href="/">home</a>
    <a href="/next">next</a>
    <a href="/profile">profile</a>
</div>

<style>
    @media print {
        .not-printable { display: none; }
    }
</style>

(如果元素分布在多个文件中,由于组件样式范围,您可能希望将其移动到全局样式表。)

pour imprimer uniqueness ton iv tu vas devoir te servir du DOM et d'une fonction javascript que tu vas créer。 ##########最终代码#########

function printMyDiv(e)
{
    var divEltToPrint = document.querySelector(".classNameOfDiv");
    var contentOfDivEltToPrint = divEltToPrint.innerHTML;
    var myWindow = window.open('', '', 'height=900px, width=600px');
    myWindow.document.write("<html><head><title>printElement</title></head><body>");
    myWindow.document.write(contentOfDivEltToPrint);
    myWindow.document.write("</body></html>");
    myWindow.print();
    myWindow.close();
}
document.querySelector(".btnPrint").addEventListener("click",printMyDiv);

Après avoir créer une fonction javascript,y ajouter les éléments en suivant les étapes:

1- tu crées une variable pour récupérer ton div a imprimer

var divEltToPrint = document.querySelector(".classNameOfDiv");

2- tu recupères le contenue html de ton div

var contentOfDivEltToPrint = divEltToPrint.innerHTML;

3- tu crées une nouvelle f.netre (c'est cette fenêtre qui sera imprimer) que tu affectes à une variable pour pouvoir la manipuler。

var myWindow = window.open('', '', 'height=900px, width=600px');

4-tu ajoutes les éléments du DOM à ta nouvelle fenêtre;

myWindow.document.write("<html><head><title>printElement</title></head><body>");

5- 继续维护 DOM 的基础和结构:

myWindow.document.write(contentOfDivEltToPrint);
myWindow.document.write("</body></html>");

6- tu lances l'impression de ta fenêtre et en suite tu la fermes

myWindow.print();
myWindow.close();

7- tu rajoutes cette fonction a ton bouton d'impression et c'est bon:!! :)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM