如何打印网页的一部分,包括所选内容

时间:2017-01-29 07:48:12

标签: javascript html css

我正在尝试打印网页的特定部分。但是每当我尝试打印它时,它都不会显示我选择的单选按钮,文本框中的内容或我从下拉菜单中选择的内容。您能告诉我如何在以下代码中实现这一目标

<html>
    <head>       
    <script>
        printDivCSS = new String ('<link href="myprintstyle.css" rel="stylesheet" type="text/css">')
        function printDiv(divId) {
            window.frames["print_frame"].document.body.innerHTML=printDivCSS + document.getElementById(divId).innerHTML;
            window.frames["print_frame"].window.focus();
            window.frames["print_frame"].window.print();
        }
    </script>
    </head>

    <body>
        <p>Some information that doesn't need to be printed</p>

        <div id="div1">This is the Part that need to be printed<br>
        <input type="radio" name="gender" value="male"> Male<br>
        <input type="radio" name="gender" value="female"> Female<br>
        <input type="radio" name="gender" value="other"> Other
        <br>
        <select>
        <option value="empty"> </option>
        <option value="volvo">Volvo</option>
        <option value="saab">Saab</option>
        <option value="opel">Opel</option>
        <option value="audi">Audi</option>
        </select>
        <p>Print out need to show the gender and the car brand I have selected</p>
        </div>        
        <iframe name="print_frame" width="0" height="0" frameborder="0" src="about:blank"></iframe>
        <b>Click here to Print:</b> <a href="javascript:printDiv('div1')">Print</a><br>
    </body>
</html>

enter image description here

请尽可能使用示例代码向我显示

1 个答案:

答案 0 :(得分:0)

如果有不受欢迎的div只放@media printdisplay:none;,您可以使用此一个。正如您在打印uwanted-div时看到的那样,按钮未显示。

@media print
   {
      .unwanted-div, button{
      display:none;  
      }       
   }
<html>
    <body>
        <div class="unwanted-div">
          Some information that doesn't need to be printed</p>
      </div>

        <div id="div1">This is the Part that need to be printed<br>
        <input type="radio" name="gender" value="male"> Male<br>
        <input type="radio" name="gender" value="female"> Female<br>
        <input type="radio" name="gender" value="other"> Other
        <br>
        <select>
        <option value="empty"> </option>
        <option value="volvo">Volvo</option>
        <option value="saab">Saab</option>
        <option value="opel">Opel</option>
        <option value="audi">Audi</option>
        </select>
        <p>Print out need to show the gender and the car brand I have selected</p>
        </div>        
        <button onclick="myFunction()">Print this page</button>

<script>
function myFunction() {
    window.print();
}
</script>
    </body>
</html>