Javascript 如何将div打印出来?

Javascript 如何将div打印出来?,javascript,html,printing-web-page,Javascript,Html,Printing Web Page,如何使用Javascript打印页面中的特定div document.write+变量和somecontent+ Javascript不会打印。必须将div插入DOM文档对象模型的某个位置 我建议学习一些jQuery并使用.append、.prepend或.html函数。我建议使用一个“打印”css样式表,在该样式表中,您可以指定隐藏您不想打印的dom元素,并显示:无。尝试仅使要打印的div在打印样式表中可见 另一种选择是使用一个弹出窗口,当点击页面中的“打印”按钮时显示该窗口。在弹出窗口中,仅

如何使用Javascript打印页面中的特定div

document.write+变量和somecontent+

Javascript不会打印。必须将div插入DOM文档对象模型的某个位置


我建议学习一些jQuery并使用.append、.prepend或.html函数。

我建议使用一个“打印”css样式表,在该样式表中,您可以指定隐藏您不想打印的dom元素,并显示:无。尝试仅使要打印的div在打印样式表中可见


另一种选择是使用一个弹出窗口,当点击页面中的“打印”按钮时显示该窗口。在弹出窗口中,仅显示div内容,并在加载文档时触发打印对话框

这是一个已经在windows上的IE8和FF3.6.6中测试过的实现 有一些东西可以简化,但其他的东西是必要的显示:iframe上的任何东西都不会打印任何内容

<html>
  <head>
  <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
  <title>print selected paragraphs</title>
  <style>
  a{text-decoration:none}
  </style>

  <style media="print">
  .noPrint { display:none}
  .print { display:block}
  </style>
  <script>
  function addPrint() {
    var checks = document.getElementsByTagName('input');
    for (var i=0;i<checks.length;i++) {
      document.getElementById(checks[i].value).className = (checks[i].checked)?'print':'noPrint';
    }
  }
  var content
  function printThis(id) {
    var iFrame = document.createElement('iframe');
    iFrame.height='1px';
    iFrame.width='1px';
    content = document.getElementById(id).innerHTML;
    content = '<body onload="self.focus();self.print()"><style>.noprint{display:none}</style>'+content+'</body>'
    iFrame.src='about:blank';
    document.body.appendChild(iFrame);
   // Initiate the iframe's document to null
     iFrame.doc = null;

     // Depending on browser platform get the iframe's document, this is only
     // available if the iframe has already been appended to an element which
     // has been added to the document
     if(iFrame.contentDocument)
      // Firefox, Opera
      iFrame.doc = iFrame.contentDocument;
     else if(iFrame.contentWindow)
      // Internet Explorer
      iFrame.doc = iFrame.contentWindow.document;
     else if(iframe.document)
      // Others?
      iFrame.doc = iFrame.document;

     // If we did not succeed in finding the document then throw an exception
     if(iFrame.doc != null) {
      iFrame.doc.write(content)
      iFrame.doc.close()
    }
    return false
  }
  window.onload=function() {
    addPrint();
  }
  </script>
  </head>
  <body>
<div id="p1" class="noPrint">
<h3>1. ¿Qué es Lorem Ipsum?</h3>
<p>Lorem Ipsum es simplemente el texto de relleno de las imprentas y archivos de texto. Lorem Ipsum ha sido el texto de relleno estándar de las industrias desde el año 1500, cuando un impresor (N. del T. persona que se dedica a la imprenta) desconocido usó una galería de textos y los mezcló de tal manera que logró hacer un libro de textos especimen. No sólo sobrevivió 500 años, sino que tambien ingresó como texto de relleno en documentos electrónicos, quedando esencialmente igual al original. Fue popularizado en los 60s con la creación de las hojas "Letraset", las cuales contenian pasajes de Lorem Ipsum, y más recientemente con software de autoedición, como por ejemplo Aldus PageMaker, el cual incluye versiones de Lorem Ipsum.</p>
<input type="checkbox" class="noPrint" id="c1" value="p1" onClick="addPrint(this)"><label class="noPrint" for="c1">Add this to print</label>&nbsp;<a href="#" onClick="return printThis('p2')">Print this NOW</a>
</div>

<div id="p2" class="noPrint">
<h3>2. ¿Por qué lo usamos?</h3>
<p>Es un hecho establecido hace demasiado tiempo que un lector se distraerá con el contenido del texto de un sitio mientras que mira su diseño. El punto de usar Lorem Ipsum es que tiene una distribución más o menos normal de las letras, al contrario de usar textos como por ejemplo "Contenido aquí, contenido aquí". Estos textos hacen parecerlo un español que se puede leer. Muchos paquetes de autoedición y editores de páginas web usan el Lorem Ipsum como su texto por defecto, y al hacer una búsqueda de "Lorem Ipsum" va a dar por resultado muchos sitios web que usan este texto si se encuentran en estado de desarrollo. Muchas versiones han evolucionado a través de los años, algunas veces por accidente, otras veces a propósito (por ejemplo insertándole humor y cosas por el estilo).</p>
<input type="checkbox" class="noPrint" id="c2" value="p2" onClick="addPrint(this)"><label class="noPrint" for="c2">Add this to Print</label>
</div>
</body>
</html>

请更具体一点你好,朋友,你想要打印输出还是软拷贝?你有什么理由想用javascript打印一个div吗?在对javascript/DOM/etc有基本了解之前学习jQuery是一个解决问题的方法,但是用javascript打印一个div对你来说有多困难?因为你真的需要学习jQuery…:你是认真的吗?没有什么比打印样式表更好的了。