如何在JavaScript中打印呈现的HTML页面的一部分?

JavaScript代码window.print()可以打印当前的HTML页面。


如果我在HTML页面中有一个div(例如,从ASP.NET MVC视图呈现的页面),那么我只想打印div。


是否有任何jQuery 不引人注目的JavaScript或普通的JavaScript代码来实现此请求?


更清楚地说,假设呈现的HTML页面如下:


<html xmlns="http://www.w3.org/1999/xhtml">


    <head id="Head" runat="server">

        <title>

            <asp:ContentPlaceHolder runat="server" ID="TitleContent" />

        </title>

    </head>


    <body>

            <div id="div1" class="div1">....</div>

            <div id="div2" class="div2">....</div>

            <div id="div3" class="div3">....</div>

            <div id="div4" class="div4">....</div>

            <div id="div4" class="div4">....</div>

        <p>

            <input id="btnSubmit" type="submit" value="Print" onclick="divPrint();" />

        </p>

    </body>

</html>

然后我想点击打印按钮,只打印div3。


蝴蝶不菲
浏览 925回答 3
3回答

翻过高山走不出你

我会有点像这样:<html>&nbsp; &nbsp; <head>&nbsp; &nbsp; &nbsp; &nbsp; <title>Print Test Page</title>&nbsp; &nbsp; &nbsp; &nbsp; <script>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; printDivCSS = new String ('<link href="myprintstyle.css" rel="stylesheet" type="text/css">')&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; function printDiv(divId) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; window.frames["print_frame"].document.body.innerHTML=printDivCSS + document.getElementById(divId).innerHTML;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; window.frames["print_frame"].window.focus();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; window.frames["print_frame"].window.print();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; </script>&nbsp; &nbsp; </head>&nbsp; &nbsp; <body>&nbsp; &nbsp; &nbsp; &nbsp; <h1><b><center>This is a test page for printing</center></b><hr color=#00cc00 width=95%></h1>&nbsp; &nbsp; &nbsp; &nbsp; <b>Div 1:</b> <a href="javascript:printDiv('div1')">Print</a><br>&nbsp; &nbsp; &nbsp; &nbsp; <div id="div1">This is the div1's print output</div>&nbsp; &nbsp; &nbsp; &nbsp; <br><br>&nbsp; &nbsp; &nbsp; &nbsp; <b>Div 2:</b> <a href="javascript:printDiv('div2')">Print</a><br>&nbsp; &nbsp; &nbsp; &nbsp; <div id="div2">This is the div2's print output</div>&nbsp; &nbsp; &nbsp; &nbsp; <br><br>&nbsp; &nbsp; &nbsp; &nbsp; <b>Div 3:</b> <a href="javascript:printDiv('div3')">Print</a><br>&nbsp; &nbsp; &nbsp; &nbsp; <div id="div3">This is the div3's print output</div>&nbsp; &nbsp; &nbsp; &nbsp; <iframe name="print_frame" width="0" height="0" frameborder="0" src="about:blank"></iframe>&nbsp; &nbsp; </body></html>

神不在的星期二

试试这个JavaScript代码:function printout() {&nbsp; &nbsp; var newWindow = window.open();&nbsp; &nbsp; newWindow.document.write(document.getElementById("output").innerHTML);&nbsp; &nbsp; newWindow.print();}
打开App,查看更多内容
随时随地看视频慕课网APP