JQuery是一種廣泛應(yīng)用的JavaScript庫,它封裝了許多常用的JavaScript功能,使得JavaScript編程更加便捷。其中,jQuery Word導(dǎo)出插件是一項非常實用的功能,可以將網(wǎng)頁內(nèi)容導(dǎo)出為Word文檔,方便用戶進(jìn)行保存和分享。
// 初始化 Word導(dǎo)出插件 $("#export").click(function () { $("#yourContent").wordExport("your content"); }); // Word導(dǎo)出插件代碼 (function ($) { $.fn.extend({ wordExport: function (fileName) { fileName = typeof fileName !== "undefined" ? fileName : "document"; var static = { mhtml: { top: "Mime-Version: 1.0\nContent-Base: " + location.href + "\nContent-Type: Multipart/related; boundary=\"NEXT.ITEM-BOUNDARY\";type=\"text/html\"\n\n--NEXT.ITEM-BOUNDARY\nContent-Type: text/html; charset=\"utf-8\"\nContent-Location: " + location.href + "\n\n\n\n_html_", head: "\n\n\n\n", body: "_body_" } }; var options = { maxWidth: 624 }; var markup = $(this).clone(); markup.each(function () { var self = $(this); if (self.is(":visible") === false) { self.remove(); return; } }); var images = Array(); var img = markup.find("img"); for (var i = 0; i< img.length; i++) { // Calculate dimensions of output image var w = Math.min(img[i].width, options.maxWidth); var h = img[i].height * (w / img[i].width); // Create canvas for converting image to data URL var canvas = document.createElement("CANVAS"); canvas.width = w; canvas.height = h; // Draw image to canvas var context = canvas.getContext("2d"); context.drawImage(img[i], 0, 0, w, h); // Get data URL encoding of image var uri = canvas.toDataURL("image/png"); $(img[i]).attr("src", img[i].src); img[i].width = w; img[i].height = h; // Save encoded image to array images[i] = { type: uri.substring(uri.indexOf(":") + 1, uri.indexOf(";")), encoding: uri.substring(uri.indexOf(";") + 1, uri.indexOf(",")), location: $(img[i]).attr("src"), data: uri.substring(uri.indexOf(",") + 1) }; } // Prepare bottom of mhtml file with image data var mhtmlBottom = "\n"; for (var i = 0; i< images.length; i++) { mhtmlBottom += "--NEXT.ITEM-BOUNDARY\n"; mhtmlBottom += "Content-Location: " + images[i].location + "\n"; mhtmlBottom += "Content-Type: " + images[i].type + "\n"; mhtmlBottom += "Content-Transfer-Encoding: " + images[i].encoding + "\n\n"; mhtmlBottom += atob(images[i].data); mhtmlBottom += "\n\n"; } // Replace CSS links with inline styles var styles = ""; $("style").each(function () { styles += $(this)[0].outerHTML; }); styles = styles.replace(/