仅打印页面上的选定项目

Print only selected items on a page

本文关键字:项目 打印      更新时间:2023-09-26

我被要求为动态生成的页面提供一些棘手的打印功能。该页面将显示每条记录以及一个复选框。然后在页面底部有一个打印按钮。这个想法是让用户选中他们要打印的每条记录旁边的框,然后当他们单击页面底部的打印按钮时,只会打印那些选定的记录。

我假设需要CSS和Javascript的某种组合,但我真的不知道。有什么想法吗?提前感谢!

PHP 解决方案

如果你有类似的东西

<form method="post" action="print.php">
  <p>Select the records to be printed</p>
  <p>
    <input type="checkbox" name="records[]" value="1"><div class="record">Record 1</div><br>
    <input type="checkbox" name="records[]" value="2"><div class="record">Record 2</div><br>
    <input type="checkbox" name="records[]" value="3"><div class="record">Record 3</div>
  </p>
</form>

您将在 php 脚本print.php中自动获得一个数组$_POST['records']其中包含所选记录的所有值。(请注意,仅当所有复选框的名称相同并以 [] 结尾时,这才有效(

然后,php 脚本可以执行以下操作:

<?php
foreach ($record in $_POST['records']) {
    // fetch the record with id $record from the database (or similar)
    // print this record to the page
}
echo "<script>window.print();</script>"; // or put that into the onload attribute of the body tag
?>

JavaScript 和 CSS

另一个有效的可能性是通过javascript完成整个事情。因此,如果在单击打印按钮时选中每个复选框,然后删除或隐藏所有未选中的记录,则必须选中每个复选框。

一个有用的东西是css属性media,您可以使用它定义仅适用于某些设备的额外样式。这段代码可以在没有任何javascript的情况下做所有事情,除了打印按钮中onclick="window.print()"的属性:

@media print {
    input{
        display: none;  /* hides all input elements for the printer */
    }
    .record {
        display: none;  /* hide all records by default */
    }
    input[checked] + .record, input:checked + div.record {
        /* display all that are immediately preceeded by a input with checked attribute */
        display: block;  
    }
}

请注意,我只在 Safari 中测试了它(伪类 :checked 导致想要的结果而不是属性选择器(,并且仅适用于支持 css3 和选择器的较新版本的浏览器。

创建一个将表单发布到的print.php(带有选定的复选框( - 页面将仅显示所选内容,与您希望它在打印中的外观完全相同,然后调用 JavaScript window.print()加载。