点击文件输入时如何检测取消? [英] How to detect when cancel is clicked on file input?

查看:127
本文介绍了点击文件输入时如何检测取消?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何检测用户何时使用html文件输入取消文件输入?

How can I detect when the user cancels a file input using an html file input?

onChange可让我检测何时选择文件,但我也希望知道他们什么时候取消(关闭文件选择对话框而不选择任何东西)。

onChange lets me detect when they choose a file, but I would also like to know when they cancel (close the file choose dialog without selecting anything).

推荐答案

虽然不是直接的解决方案,也是坏的因为它只有(就我所测试的)使用onfocus(需要一个非常有限的事件阻塞),您可以通过以下方式实现:

While not a direct solution, and also bad in that it only (as far as I've tested) works with onfocus (requiring a pretty limiting event blocking) you can achieve it with the following:

document.body.onfocus = function(){ /*rock it*/ }

这是什么好的,你可以随着文件事件及时附加/分离,并且隐藏的输入似乎也可以正常工作(如果您使用可视化的解决方法来获取错误的默认输入类型= '文件')。之后,您只需要确定输入值是否改变。

What's nice about this, is that you can attach/detach it in time with the file event, and it also seems to work fine with hidden inputs (a definite perk if you're using a visual workaround for the crappy default input type='file'). After that, you just need to figure out if the input value changed.

一个例子:

var godzilla = document.getElementById('godzilla')

godzilla.onclick = charge

function charge()
{
    document.body.onfocus = roar
    console.log('chargin')
}

function roar()
{
    if(godzilla.value.length) alert('ROAR! FILES!')
    else alert('*empty wheeze*')
    document.body.onfocus = null
    console.log('depleted')
}

看到它在行动中: http://jsfiddle.net/Shiboe/yuK3r/6/

可悲的是,在webkit浏览器上工作。也许别人可以找出firefox / IE解决方案

Sadly, it only seems to work on webkit browsers. Maybe someone else can figure out the firefox/IE solution

这篇关于点击文件输入时如何检测取消?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆