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

前端 未结 28 1970
囚心锁ツ
囚心锁ツ 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 06:42

    For those who understand that you have to overlay an invisible form over the link, but are too lazy to write, I wrote it for you. Well, for me, but might as well share. Comments are welcome.

    HTML (Somewhere):

    File Browse
    

    HTML (Somewhere you don't care about):

    JavaScript:

    function pageY(el) {
        var ot = 0;
        while (el && el.offsetParent != el) {
            ot += el.offsetTop ? el.offsetTop : 0;
            el = el.offsetParent;
        }
        return ot;
    }
    
    function pageX(el) {
        var ol = 0;
        while (el && el.offsetParent != el) {
            ol += el.offsetLeft ? el.offsetLeft : 0;
            el = el.offsetParent;
        }
        return ol;
    }
    
    function fileMove() {
        if (navigator.appName == "Microsoft Internet Explorer") {
            return; // Don't need to do this in IE. 
        }
        var link = document.getElementById("fileLink");
        var form = document.getElementById("uploadForm");
        var x = pageX(link);
        var y = pageY(link);
        form.style.position = 'absolute';
        form.style.left = x + 'px';
        form.style.top = y + 'px';
    }
    
    function fileBrowse() {
        // This works in IE only. Doesn't do jack in FF. :( 
        var browseField = document.getElementById("uploadForm").file;
        browseField.click();
    }
    

提交回复
热议问题