類比input type=file

來源:互聯網
上載者:User

表單中的input type=”file”在前端開發中經常會用到,但是很悲劇的是input type=”file”在各個瀏覽器下表現不統一,樣式很難起作用;

通常我的設計師是非常愛美的,如果真的要還原設計稿,只能通過文字框和按鈕去類比一個input type=”file”。

HTML代碼如下:

<div class="type-file-box">
<form action="" method="post" name="form1" id="form1">
<input name="fileField" type="file" id="fileField" size="28" />

</form>
</div>

這是一個基本的input type=”file”。當然這裡你可能沒看到文字框和按鈕的代碼,我們可以在後面的js中將文字框和按鈕追加到html中。

注意:size=”28″是在firefox下input type=”file”的寬高是不能通過樣式來定義的,所以用了size屬性來控制input type=”file”的寬度

CSS代碼如下:

.type-file-box {
    position:relative;
    width:260px
}
input {
    vertical-align:middle;
    margin:0;
    padding:0
}
.type-file-text {
    height:22px;
    border:1px solid #cdcdcd;
    width:180px;
}
.type-file-button {
    background-color:#FFF;
    border:1px solid #CDCDCD;
    height:24px;
    width:70px;
}
.type-file-file {
    position:absolute;
    top:0;
    right:0;
    height:24px;
filter:alpha(opacity:0);
    opacity: 0;
    width:260px
}

 
注意:這裡的filter:alpha(opacity:0);opacity: 0是讓input
type=”file”全透明,這樣使用者看不到input
type=”file”。層級在文字框和按鈕之上。這樣使用者在點擊按鈕的時侯實際上點擊的input type=”file”;js代碼:
$(function () {
    var textButton = "<input type='text' name='textfield' id='textfield' class='type-file-text' /> &nbsp;<input type='submit' name='button' id='button' value='瀏覽...' class='type-file-button' />"
    $(textButton).insertBefore("#fileField");
    $("#fileField").change(function () {
        $("#textfield").val($("#fileField").val());););
這裡用了jq當input type=”file”得值onchange的的時侯將文字框的值設定成input type=”file”的值,OK了demo示範:http://www.css88.com/demo/input-file/

聲明: 本文採用 BY-NC-SA 協議進行授權 | WEB前端開發
轉載請註明轉自《類比input type=file》

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.