javascript打印特定的div

标签 javascript jquery css

我从这个网站得到这段代码来打印一个 div:

    function printData()
{
   var divToPrint=document.getElementById("printTable");
   newWin= window.open("");
   newWin.document.write(divToPrint.outerHTML);
   newWin.print();

   newWin.close();
}

$('button').on('click',function(){
printData();
})

如何将 css 代码添加到此 javascript 以应用于 id='table' 的表?

table, td, th {
    border: 1px solid black;
    text-align:justify;
}

th {
    background-color: #7a7878;
    text-align:center
}

最佳答案

请看:http://jsfiddle.net/rhjv1u11/

 function printData()
{
   var divToPrint=document.getElementById("printTable");
   newWin= window.open("");
   newWin.document.write(divToPrint.outerHTML);
    var css =`table, td, th {
        border: 1px solid black;
        text-align:justify;
    }

    th {
        background-color: #7a7878;
        text-align:center
    }`;
   var div = $("<div />", {
    html: '&shy;<style>' + css + '</style>'
  }).appendTo( newWin.document.body);
   newWin.print();

   newWin.close();
}

$('button').on('click',function(){
printData();
});

该示例仅插入包含您的规则的样式元素。 如果您需要分配的 CSS 与示例所建议的一样少(并且不需要大量维护),那么这是一个足够的解决方案。

如果它更复杂,您应该访问 newWin.document.head 并插入一个节点来加载外部 CSS。这看起来像这样:

var linkElement=document.createElement("link");

linkElement.setAttribute("rel", "stylesheet");
linkElement.setAttribute("type", "text/css");
linkElement.setAttribute("href", "your.css.file.here.css")
newWin.document.getElementsByTagName("head")[0].appendChild(linkElement)

关于javascript打印特定的div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33462909/

相关文章:

html - Div 在 Google chrome 中不显示(在 firefox 中显示)

javascript - 如何在 React 中处理获取 API AJAX 响应

css - 表格单元格上的绝对元素

javascript - Cookie 向下滑动 div 并在重新加载时记住

javascript - 添加 "required"到选择框

javascript - 如何将工具栏中的按钮设置为禁用

javascript - 当我将员工状态更改为终止或辞职时,添加另一个字段辞职日期

html - 页脚重叠正文

Javascript 方法调用和打印

javascript - 没有jquery的自定义滚动条