如何使用css设置输入类型文件的样式

时间:2014-01-17 05:20:21

标签: jquery html css

http://jsfiddle.net/5WcFj/

我有一个输入字段,类型为“file”。

     <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;   
}

我的输出如下

enter image description here 但实际上我希望输出像, enter image description here 另一个问题是我只想要选择“jpeg和png”图像文件,但此输入字段接受所有文件类型。我在浏览器Firefox和Chrome中都尝试了这个功能

3 个答案:

答案 0 :(得分:2)

<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);
    }
});

试试这个

http://jsfiddle.net/jogesh_pi/5WcFj/2/

答案 1 :(得分:1)

尝试此操作验证文件

var ext = $('#file').val().split('.').pop().toLowerCase();
if($.inArray(ext, ['gif','png','jpg','jpeg']) == -1) {
   alert('invalid extension!');
}

答案 2 :(得分:1)

要回答第二个问题,您可以使用accept上的input属性选择打开框中显示的文件。

请参阅official W3C reference

但请注意,该页面建议您可以使用accept="image/png,image/jpeg"选择png和jpeg文件,但这并不适用于所有浏览器。实际上只在Chrome中。所以最好放置accept="image/*"(对于所有图像文件),这在大多数浏览器中都有效。

小提琴here

您也遇到了提交按钮的问题,但这是因为<input type="button"><button>不同。一个不提交,另一个提交。
这是一个快速列表供参考。

<input type="submit"> 提交
<input type="button"> 未提交
<button type="submit">提交了 <button type="button">未提交
<button>              提交