jQuery trigger file input

后端 未结 21 1574
梦如初夏
梦如初夏 2020-11-22 08:49

Am trying to trigger an upload box (browse button) using jQuery.
The method I have tried now is:

$(\'#fileinput\').trigger(\'click\');   
21条回答
  •  伪装坚强ぢ
    2020-11-22 09:07

    this worked for me:

    JS:

    $('#fileinput').trigger('click'); 
    

    HTML:

    CSS:

    .hiddenfile {
     width: 0px;
     height: 0px;
     overflow: hidden;
    }
    

    >>>Another one that works Cross-Browser:<<<

    The Idea is that you overlay an invisible huge "Browse" button over your custom button. So when the user clicks your custom button, he's actually clicking on the "Browse" button of the native input field.

    JS Fiddle: http://jsfiddle.net/5Rh7b/

    HTML:

    Click Me!

    CSS:

    div#mybutton {
    
      /* IMPORTANT STUFF */
      overflow: hidden;
      position: relative;   
    
      /* SOME STYLING */
      width:  50px;
      height: 28px;
      border: 1px solid green;
      font-weight: bold
      background: red;
    }
    
    div#mybutton:hover {
      background: green;
    }
    
    input#myfile {
      height: 30px;
      cursor: pointer;
      position: absolute;
      top: 0px;
      right: 0px;
      font-size: 100px;
      z-index: 2;
    
      opacity: 0.0; /* Standard: FF gt 1.5, Opera, Safari */
      filter: alpha(opacity=0); /* IE lt 8 */
      -ms-filter: "alpha(opacity=0)"; /* IE 8 */
      -khtml-opacity: 0.0; /* Safari 1.x */
      -moz-opacity: 0.0; /* FF lt 1.5, Netscape */
    }
    

    JavaScript:

    $(document).ready(function() {
        $('#myfile').change(function(evt) {
            alert($(this).val());
        });
    });
    

提交回复
热议问题