file对象选中同一个文件如何触发change事件

  html file控件的onchange事件,在选中同一个文件时是不会触发的。要想file选中同一个文件onchange事件也触发,可以创建一个新file对象,透明浮动覆盖在显示的file对象上,这样操作的就是新file对象,即使选中同一个文件也会触发onchange事件了。

注意:提交表单时需要移除那个透明的同名file对象,要不服务器端使用name来获取控件会出错。

  file对象选中同一个文件如何触发change事件源代码如下

<style>
div.file{display:inline-block;position:relative;}
div.file input.transparent{position:absolute;left:0;top:0;filter:alpha(opacity=0);opacity:0;width:100%}
</style>
<!--IE6,IE7 css hack-->
<!--[if lte IE 7]><style>div.file{display:inline}</style><![endif]-->
<script>
    function changeEvent(o) {
        alert(o.value);
        var newfile = document.createElement('input');
        newfile.onchange = function () { changeEvent(this) }
        newfile.type = 'file';
        newfile.className = 'transparent';
        o.parentNode.appendChild(newfile);//添加新透明file对象
        if (o.previousSibling) {//操作的是透明file对象
            o.parentNode.removeChild(o.previousSibling);//删除显示的file对象
            o.className = '';//透明对象显示出来
        }
    }
</script>
<div class="file"><input type="file" onchange="changeEvent(this)" /></div>

 

加支付宝好友偷能量挖...


原创文章,转载请注明出处:file对象选中同一个文件如何触发change事件

评论(0)Web开发网
阅读(1002)喜欢(0)JavaScript/Ajax开发技巧