In JavaScript can I make a “click” event fire programmatically for a file input element?

前端 未结 28 1332
囚心锁ツ
囚心锁ツ 2020-11-21 06:29

I\'d like to make a click event fire on an tag programmatically.

Just calling click() doesn\'t seem to do anything or at lea

28条回答
  •  我在风中等你
    2020-11-21 07:00

    WORKING SOLUTION

    Let me add to this old post, a working solution I used to use that works in probably 80% or more of all browsers both new and old.

    The solution is complex yet simple. The first step is to make use of CSS and guise the input file type with "under-elements" that show through as it has an opacity of 0. The next step is to use JavaScript to update its label as needed.

    HTML The ID's are simply inserted if you wanted a quick way to access a specific element, the classes however, are a must as they relate to the CSS that sets this whole process up

    CSS Keep in mind, coloring and font-styles and such are totally your preference, if you use this basic CSS, you can always use after-end mark up to style as you please, this is shown in the jsFiddle listed at the end.

    .file-test-area {
        border: 1px solid;
        margin: .5em;
        padding: 1em;
    }
    .file-input {
        cursor: pointer !important;
    }
    .file-input * {
        cursor: pointer !important;
        display: inline-block;
    }
    .file-input.wrapper {
        display: inline-block;
        font-size: 14px;
        height: auto;
        overflow: hidden;
        position: relative;
        width: auto;
    }
    .file-input.control {
        -moz-opacity:0 ;
        filter:alpha(opacity: 0);
        opacity: 0;
    
        height: 100%;
        position: absolute;
        text-align: right;
        width: 100%;
        z-index: 2;
    }
    .file-input.content {
        position: relative;
        top: 0px;
        left: 0px;
        z-index: 1;
    }
    .file-input.output {
        background-color: #FFC;
        font-size: .8em;
        padding: .2em .2em .2em .4em;
        text-align: center;
        width: 10em;
    }
    .file-input.button {
        border: none;
        font-weight: bold;
        margin-left: .25em;
        padding: 0 .25em;
    }
    

    JavaScript Pure and true, however, some OLDER (retired) browsers may still have trouble with it (like Netscrape 2!)

    var inp = document.getElementsByTagName('input');
    for (var i=0;i

    Working jsFiddle Example

提交回复
热议问题