[英]How to style input type file using css
我有一个输入字段,其类型为“文件”。
<input type="text" name="fake_section" class="fake_section"><button class="fake_section">Choose Photo</button>
<input type="file" style="display:none;" name="file" id="file" value="Choose Photo" accept="image/png,image/jpeg" />
<input type="submit" name="submit" value="Submit" />
我用下面的CSS
input[type="file"] {
width:50%;
height:25px;
border-radius:2px;
display:inline-block;
border:thin solid #ddd;
}
我得到了我的输出如下
但实际上我希望输出像
另一个问题是我只想选择“ jpeg和png”图像文件 ,但是此输入字段接受所有文件类型。 我在Firefox和Chrome浏览器中都尝试过
<input type="text" name="fake_section" class="fake_section">
<input type="button" class="fake_section" value="Choose Photo"/>
<input type="file" style="display:none;" name="file" id="file" value="Choose Photo" accept="image/png,image/jpeg" />
<input type="submit" name="submit" value="Submit" />
JS
$('.fake_section').click(function(e){
e.preventDefault();
$('#file').trigger('click');
});
$('#file').change(function(e){
var filename = $(this).val();
var ext = filename.split('.').pop().toLowerCase();
if( $.inArray( ext, ['gif','jpg','jpeg'] ) == -1 ){
alert('not valid!');
}
else{
$('input[name="fake_section"]').val(filename);
}
});
这样尝试
试试这个来验证文件
var ext = $('#file').val().split('.').pop().toLowerCase();
if($.inArray(ext, ['gif','png','jpg','jpeg']) == -1) {
alert('invalid extension!');
}
要回答第二个问题,您可以使用input
上的accept
属性来选择哪些文件显示在打开框中。
请参阅W3C官方参考 。
但是请注意,该页面建议您可以使用accept="image/png,image/jpeg"
选择png和jpeg文件,但并非在所有浏览器中都可以使用。 实际上仅在Chrome中。 因此,最好在大多数浏览器中都可以使用accept="image/*"
(对于所有图像文件)。
在这里摆弄。
您还遇到了提交按钮的麻烦,但这是由于<input type="button">
与<button>
。 一个不提交,另一个提交。
这是一个快速列表供参考。
<input type="submit">
提交
<input type="button">
不提交
<button type="submit">
提交
<button type="button">
不提交
<button>
提交
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.