我开发了我自己的插件,代码如下,一个现场示例位于http://jsfiddle.net/fyu4P/embedded/result/。
在FF 26.0上,它可以正常工作,但是在打印几次后,FF会询问用户是否禁用弹出窗口,但不希望发生这种情况。此外,它不适用于较旧的IE浏览器以及其他浏览器。不要担心,在打印时,您仍然需要点击操作系统打印对话框,这样您就不会浪费任何纸张!我已要求https://codereview.stackexchange.com/questions/39235/critique-of-jquery-plugin-which-will-print-to-a-printer-an-element-or-a-jqueryui提供任何建议。
实际插件:
/*
* jQuery printIt
* Print's the selected elements to the printer
* Copyright Michael Reed, 2014
* Dual licensed under the MIT and GPL licenses.
*/
(function($){
var defaults = {
elems :null, //Element to print HTML
copy_css :false,//Copy CSS from original element
external_css :null //New external css file to apply
};
var methods = {
init : function (options) {
var settings = $.extend({}, defaults, options)
elems=$(settings.elems);
return this.each(function() {
$(this).click(function(e) {
var iframe = document.createElement('iframe');
document.body.appendChild(iframe);
$(iframe).load(function(){
elems.each(function(){
iframe.contentWindow.document.body.appendChild(this.cloneNode(true));
});
if(settings.copy_css) {
var arrStyleSheets = document.getElementsByTagName("link");
for (var i = 0; i < arrStyleSheets.length; i++){
iframe.contentWindow.document.head.appendChild(arrStyleSheets[i].cloneNode(true));
}
var arrStyle = document.getElementsByTagName("style");
for (var i = 0; i < arrStyle.length; i++){
iframe.contentWindow.document.head.appendChild(arrStyle[i].cloneNode(true));
}
}
if(settings.external_css) {
var style = document.createElement("link")
style.rel = 'stylesheet';
style.type = 'text/css';
style.href = settings.external_css;
iframe.contentWindow.document.head.appendChild(style);
}
var script = document.createElement('script');
script.type = 'text/javascript';
script.text = 'window.print();';
iframe.contentWindow.document.head.appendChild(script);
$(iframe).hide();
});
});
});
},
destroy : function() {
//Anything else I should do here?
delete settings;
return this.each(function() {});
}
};
$.fn.printIt = function(method) {
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || ! method) {
return methods.init.apply(this, arguments);
} else {
$.error('Method ' + method + ' does not exist on jQuery.printIt');
}
};
}(jQuery)
);
配置:
$(function() {
$("#openDialog").click(function() {
$("#myDialog").dialog('open')
});
$("#myDialog").dialog({
modal: true,
autoOpen: false
});
$('#printIt').printIt({
elems: $("#myDialog"),
copy_css: true,
external_css: 'test2.css'
});
});
你能解释一下你到底想要什么吗?您是否希望将模式中的内容打印到单独的'div#'中,或者当您单击'Ok'按钮时,想要打印模式的'p'和'img'(或其他),进入警报窗口在代码中? –