1

我希望用户能够打印带有或不带有 aa div 中包含的某些信息的文档。我有 2 个样式表,其中一个指定了打印时要隐藏的 div 类的样式: .hide { display: none; }

以下是根据传递的参数选择样式表的脚本:

function print(o) {
  var head = document.getElementsByTagName('head')[0].innerHTML;
  if (o == 'withinfo') {
    head += '<link rel="stylesheet" href="printwithinfo.css" media="print" />';
 }
 if (o == 'withoutinfo') {
    head += '<link rel="stylesheet" href="printwithoutinfo.css" media="print" />';
 }
 document.getElementsByTagName('head')[0].innerHTML = head;
 }

然后在我的html中,我有以下内容:

   <div class="hide">My Info</div>

我的两个按钮如下:

   <input type="button" value="Print with info" onclick="print('withinfo');">

   <input type="button" value="Print without info" onclick="print('withoutinfo');">        

不幸的是,当我单击任何一个按钮时,什么都没有发生。你能告诉我我做错了什么吗?

4

2 回答 2

2

首先,我强烈建议您更改 func 名称,因为 print() 在 Javascript 中是保留的。

然后对我来说你的代码似乎工作正常,试试这个:

<!doctype html>
<html>
<head></head>


<body>
    <script>
        function Myprint(o) {
            var head = document.getElementsByTagName('head')[0].innerHTML;
            if (o == 'withinfo') {
              head += '<link rel="stylesheet" href="b.css" media="print" />';
           }
           if (o == 'withoutinfo') {
              head += '<link rel="stylesheet" href="a.css" media="print" />';
           }
           document.getElementsByTagName('head')[0].innerHTML = head;
           window.print();
}
    </script>
       <div id="hide">My Info</div>  
       Always here
    <input type="button" value="Print with info" onclick="Myprint('withinfo');" />
    <input type="button" value="Print without info" onclick="Myprint('withoutinfo');" />
</body>
</html>

使用 a.css:

div{display:none;}

和 b.css:

div{display:block;}
于 2013-04-17T10:29:45.457 回答
1

它似乎工作得很好。

您必须知道,当您单击任一按钮时,唯一发生的事情就是样式表会附加到头部。由于样式表仅适用于 media="print" 它只会在用户或您激活打印时应用。

如果你想激活它,你可以这样做。

<input type="button" value="Print with info" onclick="print('withinfo');window.print();"></input>
<input type="button" value="Print without info" onclick="print('withoutinfo');window.print();"></input>

如果您只是想测试正在应用的样式表,您可以删除链接标签的 (media="print") 部分。这将样式表限制为仅在“打印”中应用。

注意:您的打印功能应该更改名称,因为它会覆盖 window.print。

更好的选择

只需使用从一开始就加载且永不更改的 1 个样式表“print.css”。

然后将打印更改为此

function print(o) {
    document.getElementById("body").className = o;
}

并且在您的样式表中有以下内容

body.withinfo #hide {
    display: block;
}

body.withoutinfo #hide {
    display: none;
}

这样您就不必卸载以前的样式表,唯一改变的是 body 元素上的类。

于 2013-04-17T10:28:32.927 回答