如何使用 Knockout js 重定向到打印模板

How to re-direct to a print template using Knockout js

我在视图中使用模板,我想将用户定向到打印模板。常用用法:

<div data-bind="template: { name: 'print' }"></div>

但我希望此脚本单独出现,而不是与其他内容一起出现。 是否可以转到我的打印脚本而不是将脚本拉入 div,这就是上面的代码所做的。谢谢。

  • 您可以在 "normal" 内容周围放置一个布尔值,以便在打印模板处于活动状态时隐藏其他所有内容。 <div data-bind="visible: noprint()">main site</div>

  • 重定向到另一个包含具有自己样式的打印布局的文件。

  • 创建您的页面,使 print-css 实际上按预期呈现页面。确保打印样式始终位于 css

    的底部

    @media print { body { color: #000; background-color: #fff; } }

  • 更高级的是使用组件,您可以使用相同的数据来显示您需要的所有内容,但是当用户期望可打印视图时,只需将 screenlayout-component 切换到 printlayout-component

    <a href="#" data-bind="click: () => layoutType = 'screenlayout'">screen</a> <a href="#" data-bind="click: () => layoutType = 'printlayout'">print</a> <div data-bind="component: layoutType"></div>

这是我最后做的...

var viewModel = {
    selectedTemplate: ko.observable('ViewContent'),

    subTemplate: function (item) {
        this.selectedTemplate(item);
    },

    goBack: function () {
        this.selectedTemplate('ViewContent');
    },

    printLandscape: function () {
        this.selectedTemplate('PrintContent');
        alert("Please change page orientation to Landscape");
        javascript: window.print();
    },
}
ko.applyBindings(viewModel);
.print {
    margin: 0px;
    padding: 0px;
    width: 900px; /* or width: 9.5in; */
    height: 670px; /* height: 7in; */
    clear: both;
    page-break-after: always;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<script id="getContent" type="text/html">
    <!-- ko if: ($root.selectedTemplate() == "ViewContent") -->
        <div data-bind="template: { name: 'viewContent' }"></div>
    <!-- /ko -->
    <!-- ko if: ($root.selectedTemplate() == "PrintContent") -->
        <div data-bind="template: { name: 'printContent' }"></div>
    <!-- /ko -->
</script>

<script id="viewContent" type="text/html">
<div>Here's the view or display content</div>
<a href="#" data-bind="click: function () { $root.subTemplate('PrintContent') }">Print</a>
</script>

<script id="printContent" type="text/html">
<div><a href="#" data-bind="click: $root.printLandscape">Print</a>&nbsp;|&nbsp;<a href="#" data-bind="click: $root.goBack">Back</a></div>
<div class="print">Here's the print content</div>
</script>
<div data-bind="template: { name: 'getContent' }"></div>