How to print selected div instead complete page

后端 未结 10 1844
滥情空心
滥情空心 2020-12-13 07:43

I have two divs: div1 and div2.

Maintaining the original css styles applied to the div2 element being printed.

I don\'

相关标签:
10条回答
  • 2020-12-13 08:21
    <script type="text/javascript">
        function printDiv() {    
        var printContents = document.getElementById('Your printable div').innerHTML;
        var originalContents = document.body.innerHTML;
         document.body.innerHTML = printContents;
         window.print();
         document.body.innerHTML = originalContents;
        }
    </script>
    
    0 讨论(0)
  • 2020-12-13 08:24
    <script type="text/javascript">
        function printDiv() {    
        var printContents = document.getElementById('Your printable div').innerHTML;
        var originalContents = document.body.innerHTML;
         document.body.innerHTML = printContents;
         window.print();
         document.body.innerHTML = originalContents;
        }
    </script>
    
    0 讨论(0)
  • 2020-12-13 08:29

    Using my following solution you can print the specific div content from your web page if you don't want to print your full page.

    <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>
    

    Live Demo

    0 讨论(0)
  • 2020-12-13 08:30

    You can also do it using jQuery:

    <script>
    function printArea(){
        $('body').css('visibility', 'hidden');
        $('.div2').css('visibility', 'visible');
        window.print();
    }
    </script>
    
    0 讨论(0)
提交回复
热议问题