使用Javascript从打印视图中隐藏空字段(Hide empty fields from print view with JavaScript)

编程入门 行业动态 更新时间:2024-10-26 09:28:16
使用Javascript从打印视图中隐藏空字段(Hide empty fields from print view with JavaScript)

我有一个需要打印的表格。 但是,可能会有一些字段留空,我希望它们完全从我的打印视图中排除。 我在谈论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"); } });

更多推荐

本文发布于:2023-07-26 03:54:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1270737.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字段   视图   Hide   Javascript   empty

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!