bootstrap-prettyfile.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /*
  2. * jQuery and Bootsrap3 Plugin prettyFile
  3. *
  4. * version 2.0, Jan 20th, 2014
  5. * by episage, sujin2f
  6. * Git repository : https://github.com/episage/bootstrap-3-pretty-file-upload
  7. */
  8. ( function( $ ) {
  9. $.fn.extend({
  10. prettyFile: function( options ) {
  11. var defaults = {
  12. text : "选择文件"
  13. };
  14. var options = $.extend(defaults, options);
  15. var plugin = this;
  16. function make_form( $el, text ) {
  17. $el.wrap('<div></div>');
  18. $el.hide();
  19. $el.after( '\
  20. <div class="input-append input-group"">\
  21. <span class="input-group-btn">\
  22. <button class="btn btn-white" type="button">' + text + '</button>\
  23. </span>\
  24. <input class="input-large form-control" type="text">\
  25. </div>\
  26. ' );
  27. return $el.parent();
  28. };
  29. function bind_change( $wrap, multiple ) {
  30. $wrap.find( 'input[type="file"]' ).change(function () {
  31. // When original file input changes, get its value, show it in the fake input
  32. var files = $( this )[0].files,
  33. info = '';
  34. if ( files.length == 0 )
  35. return false;
  36. if ( !multiple || files.length == 1 ) {
  37. var path = $( this ).val().split('\\');
  38. info = path[path.length - 1];
  39. } else if ( files.length > 1 ) {
  40. // Display number of selected files instead of filenames
  41. info = "已选择了" + files.length + ' 个文件';
  42. }
  43. $wrap.find('.input-append input').val( info );
  44. });
  45. };
  46. function bind_button( $wrap, multiple ) {
  47. $wrap.find( '.input-append' ).click( function( e ) {
  48. e.preventDefault();
  49. $wrap.find( 'input[type="file"]' ).click();
  50. });
  51. };
  52. return plugin.each( function() {
  53. $this = $( this );
  54. if ( $this ) {
  55. var multiple = $this.attr( 'multiple' );
  56. $wrap = make_form( $this, options.text );
  57. bind_change( $wrap, multiple );
  58. bind_button( $wrap );
  59. }
  60. });
  61. }
  62. });
  63. }( jQuery ));