猿问

模拟点击type为file时的onchange事件

我这边要实现一个一进页面就触发type为file的点击事件,然后获得选中的图片信息,我的代码是

var _file = document.createElement("input");
_file.setAttribute("type", "file");
_file.setAttribute("style", "display:none;");
_file.setAttribute("height", "0px");
_file.setAttribute("width", "0px");
_file.setAttribute("id", "_file-id");document.body.appendChild(_file);document.getElementById('_file-id').click();document.getElementById('_file-id').onchange = function(e) {
    alert(1)
}

这么写,怎么看都没错,可是在谷歌浏览器上直接不触发file的点击事件,在ie浏览器上,触发了点击事件,但是当我选中图片的时候,并没有执行onchange事件,求大神告知正确写法,可以兼容这两种浏览器,万分感谢!


叮当猫咪
浏览 853回答 1
1回答

至尊宝的传说

测试结果:Google Chrome版本 71.0.3578.98(正式版本) (64 位)Firefox Quantum 64.0 (64 位)IE 11.194.17763.0 测试不通过个人观点:关于兼容性,建议去找开源框架去做比较好,个人实现总是会有很多意想不到的问题。
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答