Workaround for file input label click (Firefox)

2019-01-21 20:36发布

<label for="input">Label</label><input type="file" id="input"/>

In Firefox 7 it is not possible to trigger the open file dialog by clicking on the label.

This SO question is very similar but that's green checked with it's a bug in FF. I'm looking for a workaround.

Any ideas?

9条回答
家丑人穷心不美
2楼-- · 2019-01-21 21:39

you can dispatch the event from any event to the type=file input if you want make the input display:none and visibility:hidden, and then dispatch the event from, say, the click|touch of an image ...

<img id="customImg" src="file.ext"/>
<input id="fileLoader" type="file" style="display:none;visibility:hidden"/>

<script>
    customImg.addEventListener(customImg.ontouchstart?'touchstart':'click', function(e){
        var evt = document.createEvent('HTMLEvents');
        evt.initEvent('click',false,true);
        fileLoader.dispatchEvent(evt);
    },false);
</script>
查看更多
疯言疯语
3楼-- · 2019-01-21 21:40

A work around when you don't need/want to have the input box (like image upload) is to use opacity: 0 in the element and use pointer-events: none; in the label. The solution is really design specific but maybe should work for someone who comes to this. (until now the bug doesn't been fixed)

http://codepen.io/octavioamu/pen/ByOQBE

查看更多
Melony?
4楼-- · 2019-01-21 21:43

Reverse the order of the label and input elements. iow, put the label element after the input element.

查看更多
登录 后发表回答