我有一个需要打印的表格。 但是,可能会有一些字段留空,我希望它们完全从我的打印视图中排除。 我在谈论Javascript window.print(); 功能和它打开的打印窗口。
有没有办法可以做这样的事情? 有没有办法在这样的事件中处理逻辑(即在打印之前?)。
帮助将不胜感激。
I have a form that requires printing. However, there might be fields that will be left blank and I would like them to be excluded from my print view altogether. I am talking about the JavaScript window.print(); function and the print window that it opens.
Is there a way I can do something like this? Is there a way for me to handle logic in such events (ie. before print?).
最满意答案
你可以使用CSS @media结合一些javascript来改变类,这取决于字段是否为空。 这样的东西......
var fields = document.getElementsByClassName("field"); for(var i=0; i < fields.length; i++){ fields[i].addEventListener('keyup', function() { if(this.value.length) { this.parentElement.className = ""; } else { this.parentElement.className = "empty"; } }); }@media print { .empty { display: none; } }<div class="empty">Name: <input class="field"></div> <div class="empty">Field: <input class="field"></div> <div class="empty">Foo: <input class="field"></div>(在片段中,向字段添加内容但不是全部,然后按ctrl + p。您将看不到打印预览中的空字段)
如果使用jQuery,你可以清理选择器并循环使js像这样
$(".field").on("keyup", function () { $this = $(this); if ($this.val().length) { $this.parent().removeClass("empty"); } else { $this.parent().addClass("empty"); } });You could use CSS @media combined with some javascript to change the class dependent on whether the field is empty or not. Something like this...
var fields = document.getElementsByClassName("field"); for(var i=0; i < fields.length; i++){ fields[i].addEventListener('keyup', function() { if(this.value.length) { this.parentElement.className = ""; } else { this.parentElement.className = "empty"; } }); }@media print { .empty { display: none; } }<div class="empty">Name: <input class="field"></div> <div class="empty">Field: <input class="field"></div> <div class="empty">Foo: <input class="field"></div>(In the snippet, add something to a field but not all and then hit ctrl+p. you wont see the empty fields in the print preview)
If using jQuery you could cleanup the selectors and looping making the js something like this
$(".field").on("keyup", function () { $this = $(this); if ($this.val().length) { $this.parent().removeClass("empty"); } else { $this.parent().addClass("empty"); } });
更多推荐
发布评论