表單中的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' /> <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》