在打印div上包含css样式

时间:2022-10-24 23:49:07

Help on jquery (rookie). I have this code to print a div and i want to include CSS on it, how to do that?

帮助jquery(菜鸟)。我有这个代码打印div,我想在其上包含CSS,该怎么做?

<script language="javascript">
function printDiv(divName) {
 var printContents = document.getElementById(divName).innerHTML;
 var originalContents = document.body.innerHTML;

 document.body.innerHTML = printContents;

 window.print();

 document.body.innerHTML = originalContents;
}
</script>

2 个解决方案

#1


1  

You can change the values on style property. For example:

您可以更改style属性的值。例如:

function printDiv(divName) {
         document.getElementById(divName).style.color = 'red';
         var printContents = document.getElementById(divName).innerHTML;
         var originalContents = document.body.innerHTML;            

         document.body.innerHTML = printContents;

         window.print();

         document.body.innerHTML = originalContents;
        }

Your div content will be red.

您的div内容将为红色。

#2


1  

got it:

function printDiv(divName) {
         document.head.insertAdjacentHTML( 'beforeend', '<link rel="stylesheet" type="text/css" href="css/style.css"/>' );
         var printContents = document.getElementById(divName).innerHTML;
         var originalContents = document.body.innerHTML;            

         document.body.innerHTML = printContents;

         window.print();

         document.body.innerHTML = originalContents;
        }

#1


1  

You can change the values on style property. For example:

您可以更改style属性的值。例如:

function printDiv(divName) {
         document.getElementById(divName).style.color = 'red';
         var printContents = document.getElementById(divName).innerHTML;
         var originalContents = document.body.innerHTML;            

         document.body.innerHTML = printContents;

         window.print();

         document.body.innerHTML = originalContents;
        }

Your div content will be red.

您的div内容将为红色。

#2


1  

got it:

function printDiv(divName) {
         document.head.insertAdjacentHTML( 'beforeend', '<link rel="stylesheet" type="text/css" href="css/style.css"/>' );
         var printContents = document.getElementById(divName).innerHTML;
         var originalContents = document.body.innerHTML;            

         document.body.innerHTML = printContents;

         window.print();

         document.body.innerHTML = originalContents;
        }