如何打印选定的div而不是完整的页面

Bha*_*mar 12 javascript jquery jquery-plugins

我有两个div:div1div2.

维护应用于div2正在打印的元素的原始css样式.

我不想在内部打印内容div1,只打印内部div2.

怎么打印?

Bha*_*dey 39

试试这个

<style type="text/css">
@media print
{
body * { visibility: hidden; }
.div2 * { visibility: visible; }
.div2 { position: absolute; top: 40px; left: 30px; }
}
</style>
Run Code Online (Sandbox Code Playgroud)


Har*_*dik 19

使用我的以下解决方案,如果您不想打印整页,可以从网页打印特定的div内容.

<html>
<head>
<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.1.min.js" > </script> 



<script type="text/javascript">

    function PrintElem(elem)
    {
        Popup($(elem).html());
    }

    function Popup(data)
    {
        var mywindow = window.open('', 'new div', 'height=400,width=600');
        mywindow.document.write('<html><head><title>my div</title>');
        /*optional stylesheet*/ //mywindow.document.write('<link rel="stylesheet" href="main.css" type="text/css" />');
        mywindow.document.write('</head><body >');
        mywindow.document.write(data);
        mywindow.document.write('</body></html>');

        mywindow.print();
        mywindow.close();

        return true;
    }

</script>
</head>
<body>

<div id="yourdiv">
    Div you want to print. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque a quam at nibh adipiscing interdum. Nulla vitae accumsan ante. 
</div>

<div>
    This will not be printed.
</div>

<div id="anotherdiv">
    Nor will this.
</div>

<input type="button" value="Print" onclick="PrintElem('#yourdiv')" />

</body>
</html>
Run Code Online (Sandbox Code Playgroud)

现场演示