the-front-end-knowledge-you-may-not-know icon indicating copy to clipboard operation
the-front-end-knowledge-you-may-not-know copied to clipboard

清空 input[type="file"] 的值

Open chbro opened this issue 7 years ago • 4 comments

let resetFileDom = dom => {
    if (({}).toString.call(dom) !== '[object HTMLInputElement]') {
        throw new Error('必须传入DOM节点')
        return
    }
    dom.value = ''
    dom.type = 'text'
    dom.type = 'file'
}

chbro avatar Apr 23 '18 07:04 chbro

直接 dom.value='' 不行吗?

xmcp avatar Apr 23 '18 12:04 xmcp

@chbro 近期我也有操作上传文件一直想清空😊。试了你的方案成功清空。👍

Youcongcong avatar Jun 09 '18 01:06 Youcongcong

@xmcp 可以直接设置为空('' | null) (chrome 69 firefox 62 edge17) https://codepen.io/Yangfan2016coding/pen/aaXoez?editors=1111

Yangfan2016 avatar Sep 20 '18 04:09 Yangfan2016

直接 dom.value='' 有兼容性问题

考虑兼容性,也可以这样

<form id="uploadField">
  <input type="file" />
</form>
window.uploadField.reset()

但是要注意 form 不能嵌套 form,最好 Portal 到其他地方

isbasex avatar Nov 01 '18 14:11 isbasex