有一个 iPhone,需要在隐藏的输入上捕获 change
事件。当在 PC 上打开时,它可以工作,我看到 changed
文本。如果我在 iPhone 上打开它没有按预期工作,我只会看到 open dialog
。
简单 jsfiddle demonstrates this .
<input type=file style="display:none" id=file>
<button type=button id=but>open</button>
<div id=out>
</div>
和
$(document).ready(function(){
$('#but').on('click touchend', function(){
$('#out').text('open dialog');
$('#file').click();
});
$('#file').on('change', function(evt) {
$('#out').text('changed');
});
});
这是怎么回事?这是iOs的新错误吗? Afaik,它在一个月前就起作用了。
我尝试将 hidden
替换为 opacity:0
,它适用于简单的 jsfiddle,但不适用于隐藏侧边栏的复杂项目。问题如下。如何进行简单的修复以及最近发生了什么变化(一些 Safari 更新?),这导致了隐藏输入行为的变化?
最佳答案
您可以使用 label
的 for
属性。
以下代码可能对您有所帮助:
$('#file').on('change', function () {
$('.button').text('changed')
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='file' style='display:none' id='file'>
<label for='file' class='button'>open</label>
使用 label
,您可以为上传按钮使用自定义样式
但是,在某些手机浏览器中,当你再次上传文件时,如果文件与之前相同,则不会触发change
事件,你使用reset
方法表单
清除文件:
$('#file').on('change', function () {
$('.form')[0].reset()
$('.button').text('changed')
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class='form'>
<input type='file' style='display:none' id='file'>
<label for='file' class='button'>open</label>
</form>
关于javascript - 为什么 iPhone 的 Safari 不会在输入类型=文件时触发更改事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45724477/