模擬input type=file
表單中的input type=”file”在前端開發中經常會用到,但是很悲劇的是input type=”file”在各個瀏覽器下表現不統一,樣式很難起作用;
通常我的設計師是非常愛美的,如果真的要還原設計稿,只能通過文本框和按鈕去模擬一個input type=”file”。
HTML代碼如下:
<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代碼如下:
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
}
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());););