我開發了我自己的插件,代碼如下,一個現場示例位於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'(或其他),進入警報窗口在代碼中? –