如何使用jQuery或JavaScript打印更改的div

时间:2012-10-15 09:14:31

标签: javascript jquery printing

我有div我可以通过更改其十六进制值来控制颜色,但是如何将其打印为我选择的颜色而不是{{1}上的原始颜色}?

例如:我的div 白色。我将颜色更改为红色,我有一个按钮,允许我打印div,但它显示我正在打印白色 {{ 1}}而不是红色

div

这是我的按钮并选择了div

<script language="JavaScript">
var gAutoPrint = true; // Tells whether to automatically call the print function

function printSpecial()
{
if (document.getElementById != null)
{
var html = '<HTML>\n<HEAD>\n';

if (document.getElementsByTagName != null)
{
var headTags = document.getElementsByTagName("head");
if (headTags.length > 0)
html += headTags[0].innerHTML;
}

html += '\n</HE>\n<BODY>\n';

var printReadyElem = document.getElementById("printReady");

if (printReadyElem != null)
{
html += printReadyElem.innerHTML;
}
else
{
alert("Could not find the printReady function");
return;
}

html += '\n</BO>\n</HT>';

var printWin = window.open("","printSpecial");
printWin.document.open();
printWin.document.write(html);
printWin.document.close();
if (gAutoPrint)
printWin.print();
}
else
{
alert("The print ready feature is only available if you are using a browser. Please
update your browser.");
}
}

</script>

2 个答案:

答案 0 :(得分:0)

如果我理解了你的问题,你可以在printSpecial()的顶部添加这行代码:

$('#printReady').css('background', '#ff0000');

控制此类事情的更好方法是使用样式。

<style>
   .ready {
     background: #ffffff;
   }

   .printing {
     background: #ff0000;
   }
</style>

然后你可以使用jQuery.addClass和jQuery.removeClass。这样你只需将你的CSS改为你想要的两种“状态”。

然后执行此操作以更改样式:

$('#printReady').removeClass('ready');
$('#printReady').addClass('printing');

然后反过来想要改回来。

答案 1 :(得分:0)

添加样式

html += '<style>* { color: red }</style>';

例如

<script language="JavaScript">
var gAutoPrint = true; // Tells whether to automatically call the print function

function printSpecial() {
  if (document.getElementById == null) return false;
  var printReadyElem = document.getElementById("printReady");
  if (printReadyElem==null) {
    alert("Could not find the printReady function");
    return false;
  }

  var html = '<HTML>\n<HEAD>\n';

  if (document.getElementsByTagName != null) {
    var headTags = document.getElementsByTagName("head");
    if (headTags.length > 0) html += headTags[0].innerHTML;
  }

  html += '<style>* { color: red }</style>';
  html += '\n</HEAD>\n<BODY>\n';
  html += printReadyElem.innerHTML;
  html += '\n</BODY>\n</HTML>';

  var printWin = window.open("","printSpecial");
  if (printWin) {
    printWin.document.write(html);
    printWin.document.close();
    if (gAutoPrint) {
      printWin.focus().print();
    }
  }    
  else {
    alert("The print ready feature is only available if you are using a browser that supports it and you have not blocked popups. Please update your browswer.");
  }
  return false;
}
</script>


this is my button and selected div

  <div id="printReady"> 

  div i want to print
  </div>

  <a href="#" onclick="return printSpecial()" style="position:absolute">Print this Page</a>