web建站教程
  1. 首页
  2. vuejs
  3. js
  4. 好玩
  5. seo教程
  6. 前端知识
  7. 百度echarts
  8. 更多
    php入门
    nodejs
    mockjs
    reactjs
    mysql
    wordpress
    织梦cms
    帝国cms
    git教程
    IT知识
    模板大全
    休息站

jQuery实现网页div局部打印(jQuery.print插件)

722 ℃
           

功能需求:做一个div局部打印,并兼容IE浏览器。

下面web建站小编给大家介绍一个可以实现div局部打印的插件jQuery.print

jQuery.print.js插件代码:

(function ($) {
  "use strict";
  // A nice closure for our definitions
  function getjQueryObject(string) {
    // Make string a vaild jQuery thing
    var jqObj = $("");
    try {
        jqObj = $(string)
            .clone();
    } catch (e) {
        jqObj = $("<span />")
            .html(string);
    }
    return jqObj;
  }
  
  function printFrame(frameWindow) {
    // Print the selected window/iframe
    var def = $.Deferred();
    try {
      setTimeout(function () {
	    // Fix for IE : Allow it to render the iframe
	    frameWindow.focus();
	    try {
	  	if (!frameWindow.document.execCommand('print', false, null)) {
	  	  frameWindow.print();
	  	}
	    } catch (e) {
	  	frameWindow.print();
	    }
	    frameWindow.close();
	    def.resolve();
	  }, 250);
    } catch (err) {
      def.reject(err);
    }
    return def;
  }
  
  function printContentInNewWindow(content) {
    // Open a new window and print selected content
    var w = window.open();
    w.document.write(content);
    w.document.close();
    return printFrame(w);
  }
  
  function isNode(o) {
    return !!(typeof Node === "object" ? o instanceof Node : o && typeof o === "object" && typeof o.nodeType === "number" && typeof o.nodeName === "string");
  }
  $.print = $.fn.print = function () {
    // Print a given set of elements
    var options, $this, self = this;
    // console.log("Printing", this, arguments);
    if (self instanceof $) {
      // Get the node if it is a jQuery object
      self = self.get(0);
    }
    if (isNode(self)) {
      // If `this` is a HTML element, i.e. for
      // $(selector).print()
      $this = $(self);
      if (arguments.length > 0) {
        options = arguments[0];
      }
    } else {
      if (arguments.length > 0) {
        // $.print(selector,options)
        $this = $(arguments[0]);
        if (isNode($this[0])) {
          if (arguments.length > 1) {
            options = arguments[1];
          }
        } else {
          // $.print(options)
          options = arguments[0];
          $this = $("html");
        }
      } else {
        // $.print()
        $this = $("html");
      }
    }
    // Default options
    var defaults = {
      globalStyles: true,
      mediaPrint: false,
      stylesheet: null,
      noPrintSelector: ".no-print",
      iframe: true,
      append: null,
      prepend: null,
      manuallyCopyFormValues: true,
      deferred: $.Deferred()
    };
    // Merge with user-options
    options = $.extend({}, defaults, (options || {}));
    var $styles = $("");
    if (options.globalStyles) {
      // Apply the stlyes from the current sheet to the printed page
      $styles = $("style, link, meta, title");
    } else if (options.mediaPrint) {
      // Apply the media-print stylesheet
      $styles = $("link[media=print]");
    }
    if (options.stylesheet) {
      // Add a custom stylesheet if given
      $styles = $.merge($styles, $('<link rel="stylesheet" href="' + options.stylesheet + '">'));
    }
    // Create a copy of the element to print
    var copy = $this.clone();
    // Wrap it in a span to get the HTML markup string
    copy = $("<span/>")
      .append(copy);
    // Remove unwanted elements
    copy.find(options.noPrintSelector)
      .remove();
    // Add in the styles
    copy.append($styles.clone());
    // Appedned content
    copy.append(getjQueryObject(options.append));
    // Prepended content
    copy.prepend(getjQueryObject(options.prepend));
    if (options.manuallyCopyFormValues) {
      // Manually copy form values into the HTML for printing user-modified input fields
      // http://stackoverflow.com/a/26707753
      copy.find("input")
        .each(function () {
          var $field = $(this);
          if ($field.is("[type='radio']") || $field.is("[type='checkbox']")) {
            if ($field.prop("checked")) {
              $field.attr("checked", "checked");
            }
          } else {
            $field.attr("value", $field.val());
          }
        });
      copy.find("select").each(function () {
        var $field = $(this);
        $field.find(":selected").attr("selected", "selected");
      });
      copy.find("textarea").each(function () {
        var $field = $(this);
        $field.text($field.val());
      });
    }
    // Get the HTML markup string
    var content = copy.html();
    // Notify with generated markup & cloned elements - useful for logging, etc
    try {
      options.deferred.notify('generated_markup', content, copy);
    } catch (err) {
      console.warn('Error notifying deferred', err);
    }
    // Destroy the copy
    copy.remove();
    if (options.iframe) {
      // Use an iframe for printing
      try {
        var $iframe = $(options.iframe + "");
        var iframeCount = $iframe.length;
        if (iframeCount === 0) {
          // Create a new iFrame if none is given
          $iframe = $('<iframe height="0" width="0" border="0" wmode="Opaque"/>')
            .prependTo('body')
            .css({
              "position": "absolute",
              "top": -999,
              "left": -999
            });
        }
        var w, wdoc;
        w = $iframe.get(0);
        w = w.contentWindow || w.contentDocument || w;
        wdoc = w.document || w.contentDocument || w;
        wdoc.open();
        wdoc.write(content);
        wdoc.close();
        printFrame(w)
          .done(function () {
            // Success
            setTimeout(function () {
              // Wait for IE
              if (iframeCount === 0) {
                // Destroy the iframe if created here
                $iframe.remove();
              }
            }, 100);
          })
          .fail(function (err) {
            // Use the pop-up method if iframe fails for some reason
            console.error("Failed to print from iframe", err);
            printContentInNewWindow(content);
          })
          .always(function () {
            try {
              options.deferred.resolve();
            } catch (err) {
              console.warn('Error notifying deferred', err);
            }
          });
      } catch (e) {
        // Use the pop-up method if iframe fails for some reason
        console.error("Failed to print from iframe", e.stack, e.message);
        printContentInNewWindow(content)
          .always(function () {
            try {
              options.deferred.resolve();
            } catch (err) {
              console.warn('Error notifying deferred', err);
            }
          });
      }
    } else {
      // Use a new window for printing
      printContentInNewWindow(content)
        .always(function () {
          try {
            options.deferred.resolve();
          } catch (err) {
            console.warn('Error notifying deferred', err);
          }
        });
    }
    return this;
  };
})(jQuery);

调用代码:

//方法1:
$('#div').print()

//方法2:
jQuery.print('#div')

//方法3:
$("#div").find('li').on('click', function() {
  $.print("#div");
});

//方法4:
$("div").find('button').on('click', function() {
  $("#ele4").print({
  	globalStyles : false,
  	mediaPrint : false,
  	stylesheet : "http://fonts.useso.com/css?family=Inconsolata",
  	iframe : false,
  	noPrintSelector : ".avoid-this",
  	prepend : "Hello World!!!<br/>",
  	append : "<br/>Buh Bye!"
  });
});

动态打印字体插件——typed.js

vuejs打印内容超过一屏自动分页

js最简单的代码实现局部打印功能(非插件)

javascript原生实现局部打印(兼容IE9)

jquery利用jqprint实现局部打印(兼容IE8)

标签: jQuery.print, 局部打印, 打印插件

上面是“jQuery实现网页div局部打印(jQuery.print插件)”的全面内容,想了解更多关于 js 内容,请继续关注web建站教程。

当前网址:https://ipkd.cn/webs_2880.html

声明:本站提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请发送到邮箱:admin@ipkd.cn,我们会在看到邮件的第一时间内为您处理!

当前位置: 网站首页 > js
本文共计5029个字,预计阅读时长34分钟
生活小工具,收录了80多款小工具
上一篇: 程序员正能量文案:乐观积极的治愈系文案,朋友圈满满向上动力句子
下一篇: Lunar组件如何利用I18n实现多语言功能
x 打工人ai神器