簡體   English   中英

如何使用CSS設置輸入類型文件的樣式

[英]How to style input type file using css

http://jsfiddle.net/5WcFj/

我有一個輸入字段,其類型為“文件”。

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

這樣嘗試

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

試試這個來驗證文件

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM