仅打印<div id ="printarea"> </ div>?

noe*_*ard 411 javascript css printing dhtml

如何打印指定的div(无需手动禁用页面上的所有其他内容)?

我想避免使用新的预览对话框,因此使用此内容创建新窗口无用.

该页面包含几个表格,其中一个表格包含我要打印的div - 该表格采用网页的视觉样式设计,不应该以打印方式显示.

Ben*_*wee 727

这是一个通用的解决方案,使用CSS,我已经验证了它的工作原理.

@media print {
  body * {
    visibility: hidden;
  }
  #section-to-print, #section-to-print * {
    visibility: visible;
  }
  #section-to-print {
    position: absolute;
    left: 0;
    top: 0;
  }
}
Run Code Online (Sandbox Code Playgroud)

替代方法并不是那么好.使用display是棘手的,因为如果有任何元素,display:none那么它的后代都不会显示.要使用它,您必须更改页面的结构.

使用visibility效果更好,因为您可以打开后代的可见性.隐形元素仍会影响布局,所以我移动section-to-print到左上方,以便正确打印.

  • 使用此解决方案需要注意的一个问题是,在某些情况下,最终可能会打印出数千个空白页.在我的情况下,我能够通过使用一些额外的显示来解决这个问题:没有选定项目的样式,但也许更通用的解决方案是通过强制高度,溢出:无和所有div或其他东西的绝对定位的某种组合可实现的. (32认同)
  • 这是迄今为止最快,最干净的方式,我想知道为什么这个答案没有得到最多的选票-.- (21认同)
  • 这是一个很好的开始,但我遇到了两个问题:如果任何元素的父母建立了自己的相对/绝对定位,那么内容仍将被抵消,除非我使用`position:fixed`代替.但是,Chrome和Safari也会截断内容,尤其是在第一页之后.所以我最后的解决方法是将目标*和*_all的parent_都设置为`overflow:visible; 位置:绝对!重要; 顶部:0;左:0` (4认同)
  • 您可以尝试使用JavaScript解决方案,但如果您的用户使用浏览器的"打印"命令,则无法使用. (2认同)

Kev*_*ida 230

用最少的代码我有一个更好的解决方案.

将您的可打印部分放在一个id为div的div中:

<div id="printableArea">
      <h1>Print me</h1>
</div>

<input type="button" onclick="printDiv('printableArea')" value="print a div!" />
Run Code Online (Sandbox Code Playgroud)

然后像onclick一样添加一个事件(如上所示),并像上面一样传递div的id.

现在让我们创建一个非常简单的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;
}
Run Code Online (Sandbox Code Playgroud)

请注意这是多么简单?没有弹出窗口,没有新窗口,没有疯狂的样式,没有像jquery这样的JS库.真正复杂的解决方案的问题(答案并不复杂,而不是我所指的)是它永远不会在所有浏览器中翻译的事实!如果要使样式不同,请通过将media属性添加到样式表链接(media ="print")来执行已检查答案中所示的操作.

没有绒毛,轻巧,它只是工作.

  • @asprin警告!这不是乱码免费代码.使用innerHTML擦除然后重新创建整个主体对于简单页面来说很好,但是通过更高级的自定义(菜单,幻灯片等),它可以擦除由其他脚本添加的一些动态行为. (90认同)
  • 此解决方案不适用于任何复杂页面,其中可打印区域中的元素取决于父元素的样式和/或位置.如果你提取可打印的div,它可能看起来完全不同,因为所有的父母现在都缺失了. (16认同)
  • @BorisGappov是一个非常简单的例子,只需点击一下即可证明我的观点:http://jsfiddle.net/dc7voLzt/我会再说一遍:这不是乱码!问题不在于打印本身,而在于恢复原始页面! (3认同)

Gre*_*reg 119

所有的答案至今都还存在缺陷-他们要么涉及添加class="noprint"到任何东西,或者会搞乱display#printable.

我认为最好的解决方案是围绕不可打印的东西创建一个包装器:

<head>
    <style type="text/css">

    #printable { display: none; }

    @media print
    {
        #non-printable { display: none; }
        #printable { display: block; }
    }
    </style>
</head>
<body>
    <div id="non-printable">
        Your normal page contents
    </div>

    <div id="printable">
        Printer version
    </div>
</body>
Run Code Online (Sandbox Code Playgroud)

当然这并不完美,因为它涉及到你的HTML中移动一些东西......

  • 我更喜欢使用语义HTML.理想情况下,打印格式应由CSS处理.请参阅我的答案:http://stackoverflow.com/questions/468881/print-div-idprintarea-div-only/2618980#2618980 (9认同)

rom*_*nsh 107

使用jQuery,它就像这样简单:

w=window.open();
w.document.write($('.report_left_inner').html());
w.print();
w.close();
Run Code Online (Sandbox Code Playgroud)

  • 诀窍是在用户生成的事件上调用它,例如鼠标单击.你也可以在第一行后添加:if(!w)alert('Please enable pop-ups'); (8认同)
  • 这非常酷,但它在Chrome中显示为阻止弹出窗口. (3认同)
  • 我用这打印时丢了css,有没有办法保持CSS? (3认同)
  • @MoxetKhan,这篇文章有一个css的解决方案http://vevlo.com/how-to-print-div-content-using-javascript/ (2认同)

Pau*_*xon 21

您可以使用打印样式表,并使用CSS来排列您想要打印的内容吗?阅读本文以获取更多信息.


Chr*_* M. 19

这很好用:

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

请注意,这仅适用于"可见性"."显示"不会这样做.在FF3中测试过.

  • 我可以免费在我的项目中使用此代码吗? (3认同)

fan*_*ite 13

我并不喜欢这些答案中的任何一个.如果你有一个类(比如printableArea)并将它作为body的直接子项,那么你可以在你的print CSS中做这样的事情:

body > *:not(.printableArea) {
    display: none;
}

//Not needed if already showing
body > .printableArea {
    display: block;
}
Run Code Online (Sandbox Code Playgroud)

使用可见性可能会导致很多间距问题和空白页面.这是因为可见性维护元素空间,只是使其隐藏,显示将其移除,并允许其他元素占用其空间.

这个解决方案的工作原理是你不是抓住所有元素,只是身体的直接孩子并隐藏它们.下面的其他解决方案使用display css,隐藏所有元素,这些元素会影响printableArea内容中的所有内容.

我不建议使用javascript,因为您需要有一个用户点击的打印按钮,标准浏览器打印按钮不会产生相同的效果.如果你真的需要这样做,我会做的是存储正文的html,删除所有不需要的元素,打印,然后再添加html.如上所述,如果可以并且使用上面的CSS选项,我会避免这种情况.

注意:您可以使用内联样式将任何CSS添加到打印CSS中:

<style type="text/css">
@media print {
   //styles here
}
</style>
Run Code Online (Sandbox Code Playgroud)

或者像我通常使用的是链接标记:

<link rel="stylesheet" type="text/css" media="print" href="print.css" />
Run Code Online (Sandbox Code Playgroud)


小智 8

  1. 给出你想要打印id的任何元素printMe.

  2. 在头标记中包含此脚本:

    <script language="javascript">
        var gAutoPrint = true;
    
        function processPrint(){
    
        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' + 'AD>\n<BODY>\n';
        var printReadyElem = document.getElementById("printMe");
    
        if (printReadyElem != null) html += printReadyElem.innerHTML;
        else{
        alert("Error, no contents.");
        return;
        }
    
        html += '\n</BO' + 'DY>\n</HT' + 'ML>';
        var printWin = window.open("","processPrint");
        printWin.document.open();
        printWin.document.write(html);
        printWin.document.close();
    
        if (gAutoPrint) printWin.print();
        } else alert("Browser not supported.");
    
        }
    </script>
    
    Run Code Online (Sandbox Code Playgroud)
  3. 调用该函数

    <a href="javascript:void(processPrint());">Print</a>
    
    Run Code Online (Sandbox Code Playgroud)


And*_*air 6

嗯...使用样式表的类型进行打印...例如:

<link rel="stylesheet" type="text/css" href="print.css" media="print" />
Run Code Online (Sandbox Code Playgroud)

print.css:

div { display: none; }
#yourdiv { display: block; }
Run Code Online (Sandbox Code Playgroud)


Har*_*ker 6

第1步:在head标签中写下以下javascript

<script language="javascript">
function PrintMe(DivID) {
var disp_setting="toolbar=yes,location=no,";
disp_setting+="directories=yes,menubar=yes,";
disp_setting+="scrollbars=yes,width=650, height=600, left=100, top=25";
   var content_vlue = document.getElementById(DivID).innerHTML;
   var docprint=window.open("","",disp_setting);
   docprint.document.open();
   docprint.document.write('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"');
   docprint.document.write('"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">');
   docprint.document.write('<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">');
   docprint.document.write('<head><title>My Title</title>');
   docprint.document.write('<style type="text/css">body{ margin:0px;');
   docprint.document.write('font-family:verdana,Arial;color:#000;');
   docprint.document.write('font-family:Verdana, Geneva, sans-serif; font-size:12px;}');
   docprint.document.write('a{color:#000;text-decoration:none;} </style>');
   docprint.document.write('</head><body onLoad="self.print()"><center>');
   docprint.document.write(content_vlue);
   docprint.document.write('</center></body></html>');
   docprint.document.close();
   docprint.focus();
}
</script>
Run Code Online (Sandbox Code Playgroud)

第2步:通过onclick事件调用PrintMe('DivID')函数.

<input type="button" name="btnprint" value="Print" onclick="PrintMe('divid')"/>
<div id="divid">
here is some text to print inside this div with an id 'divid'
</div>
Run Code Online (Sandbox Code Playgroud)


Dil*_*ngh 6

<script type="text/javascript">
   function printDiv(divId) {
       var printContents = document.getElementById(divId).innerHTML;
       var originalContents = document.body.innerHTML;
       document.body.innerHTML = "<html><head><title></title></head><body>" + printContents + "</body>";
       window.print();
       document.body.innerHTML = originalContents;
   }
</script>
Run Code Online (Sandbox Code Playgroud)

  • 看起来不错,但你打印后松开所有的javascript绑定和其他 (5认同)

小智 6

打印特定 Div 或任何元素的最佳方式

printDiv("myDiv");

function printDiv(id){
        var printContents = document.getElementById(id).innerHTML;
        var originalContents = document.body.innerHTML;
        document.body.innerHTML = printContents;
        window.print();
        document.body.innerHTML = originalContents;
}
Run Code Online (Sandbox Code Playgroud)


Joh*_*ish 6

如果没有 CSS 小丑,html 和带有 iframe 的纯 JavaScript 就能发挥最佳效果。然后只需单击您要打印的文本即可。带有文本内容的 id 元素的当前示例;

html 正文:

<div id="monitor" onclick="idElementPrint()">text i want to print</div>
Run Code Online (Sandbox Code Playgroud)

纯 JavaScript:

//or: monitor.textContent = "click me to print textual content";

const idElementPrint = () => {
    let ifram = document.createElement("iframe");
    ifram.style = "display:none";
    document.body.appendChild(ifram);
    pri = ifram.contentWindow;
    pri.document.open();
    pri.document.write(monitor.textContent);
    pri.document.close();
    pri.focus();
    pri.print();
    }
Run Code Online (Sandbox Code Playgroud)