pasteImage.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /* eslint-disable */
  2. // ------------------------------------------------------------------------
  3. // Created by STRd6
  4. // MIT License
  5. // https://github.com/distri/jquery-image_reader/blob/master/paste.coffee.md
  6. //
  7. // Raymond re-write it to javascript
  8. (function($) {
  9. $.event.fix = (function(originalFix) {
  10. return function(event) {
  11. event = originalFix.apply(this, arguments);
  12. if (
  13. event.type.indexOf('copy') === 0 ||
  14. event.type.indexOf('paste') === 0
  15. ) {
  16. event.clipboardData = event.originalEvent.clipboardData;
  17. }
  18. return event;
  19. };
  20. })($.event.fix);
  21. const defaults = {
  22. callback: $.noop,
  23. matchType: /image.*/,
  24. };
  25. return ($.fn.pasteImageReader = function(options) {
  26. if (typeof options === 'function') {
  27. options = {
  28. callback: options,
  29. };
  30. }
  31. options = $.extend({}, defaults, options);
  32. return this.each(function() {
  33. const element = this;
  34. return $(element).on('paste', function(event) {
  35. const types = event.clipboardData.types;
  36. const items = event.clipboardData.items;
  37. for (let i = 0; i < types.length; i++) {
  38. if (
  39. types[i].match(options.matchType) ||
  40. items[i].type.match(options.matchType)
  41. ) {
  42. const f = items[i].getAsFile();
  43. const reader = new FileReader();
  44. reader.onload = function(evt) {
  45. return options.callback.call(element, {
  46. dataURL: evt.target.result,
  47. event: evt,
  48. file: f,
  49. name: f.name,
  50. });
  51. };
  52. reader.readAsDataURL(f);
  53. return;
  54. }
  55. }
  56. });
  57. });
  58. });
  59. })(jQuery);