gpt4 book ai didi

javascript - 是否有从 HTML 页面打印 div 的 Angular 方式?

转载 作者:太空狗 更新时间:2023-10-29 13:06:59 25 4
gpt4 key购买 nike

我有一个使用 AngularJS 的 html 页面,我想从中打印一个 div。有 Angular 的方法吗? .. 或者它只是下面的经典 javascript 方式:

    <script language="javascript" type="text/javascript">
function printDiv(divID) {
//Get the HTML of div
var divElements = document.getElementById(divID).innerHTML;
//Get the HTML of whole page
var oldPage = document.body.innerHTML;

//Reset the page's HTML with div's HTML only
document.body.innerHTML =
"<html><head><title></title></head><body>" +
divElements + "</body>";

//Print Page
window.print();

//Restore orignal HTML
document.body.innerHTML = oldPage;
}
</script>

如果 AngularJS 对此没有任何解决办法,您能否建议一种不使用 JavaScript 函数(例如:doc.getElementById())的方法。一种接近 AngularJS 方式的方法?

谢谢,

最佳答案

我创建了一个使用 iframe 技术打印 div 内容的简单指令。这有点骇人听闻,但效果很好。我认为没有更好的方法来做到这一点。指令脚本是:

'use strict';

angular.module('yourAppNameHere').directive('printDiv', function () {
return {
restrict: 'A',
link: function(scope, element, attrs) {
element.bind('click', function(evt){
evt.preventDefault();
PrintElem(attrs.printDiv);
});

function PrintElem(elem)
{
PrintWithIframe($(elem).html());
}

function PrintWithIframe(data)
{
if ($('iframe#printf').size() == 0) {
$('html').append('<iframe id="printf" name="printf"></iframe>'); // an iFrame is added to the html content, then your div's contents are added to it and the iFrame's content is printed

var mywindow = window.frames["printf"];
mywindow.document.write('<html><head><title></title><style>@page {margin: 25mm 0mm 25mm 5mm}</style>' // Your styles here, I needed the margins set up like this
+ '</head><body><div>'
+ data
+ '</div></body></html>');

$(mywindow.document).ready(function(){
mywindow.print();
setTimeout(function(){
$('iframe#printf').remove();
},
2000); // The iFrame is removed 2 seconds after print() is executed, which is enough for me, but you can play around with the value
});
}

return true;
}
}
};
});

在您的模板中,您将打印按钮标记为这样:

<a href="#" print-div=".css-selector-of-the-div-you-want-to-print">Print!</a>

就是这样,它应该可以工作。棘手的部分是 iFrame 在一定毫秒数后被删除,因为没有跨浏览器的方法来检测打印执行的结束,因此您可以猜测它运行需要多少时间。

您可能需要包含 jQuery 才能工作,我不确定,因为没有它我几乎从不工作。我添加了一些内联注释以使事情更清楚。我使用了 this answer 中的一些代码它使用弹出窗口打印 div 内容(但在 Angular.js 之外)。也许您会更喜欢这种方法。

关于javascript - 是否有从 HTML 页面打印 div 的 Angular 方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19637312/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com