代碼很簡單,就是動態(tài)生成input標(biāo)簽,來實現(xiàn)change事件無法處理相同文件。在chrome,firefox中都有效,但在ie瀏覽器中無法觸發(fā)打印3.求助?。?!
var button=document.getElementsByClassName('button')[0];
var imgBox=document.getElementsByClassName('imgBox')[0];
button.onclick=function(){
inputImg();
}
function inputImg(){
var input=document.createElement('input');
input.type='file';
input.addEventListener('change',function(e){
console.log(3);
});
input.click();
}
ie
下click()
不能操作文檔中沒有的節(jié)點,所以你可以在click()
前添加下面的語句
document.body.appendChild( input );
input.style.display = 'none';
input.click();
要想兼容ie9
之前用attachEvent
而不是addEventListener
。
還有ie9
之前不兼容getElementsByClassName
為什么 button
使用了 .onclick
,后面的 input
卻用了 .addEventListener
呢?
在 addEventListener 文檔的 傳統(tǒng)的 Internet Explorer 及其 attachEvent 方法 有說明:
對于 Internet Explorer 來說,在IE 9之前,你必須使用 attachEvent 而不是使用標(biāo)準(zhǔn)方法
addEventListener。
IE8及以下沒有addEventListener方法 可用attachEvent()方法監(jiān)聽事件 要注意attachEvent回調(diào)中的this指向的是window哦
用下面這個來綁定事件
var addEvent = function(elem, type, handler){
if(window.addEventListener){
addEvent = function(elem, type, handler){
elem.addEventListener(type, handler, false);
};
}else if(window.attachEvent){
addEvent = function(elem, type, handler){
elem.attachEvent('on' + type, handler);
};
}
addEvent(elem, type, handler);
};
addEvent(input, "change", function(e){
alert("changed");
});