閱讀536 返回首頁    go 阿裏雲 go 技術社區[雲棲]


自定義文件上傳控件樣式-input透明法

自定義文件上傳控件樣式-input透明法。

作為一個剛入坑不久的程序小白,今天和一個自定義<input type="file">控件的工作鬥智鬥勇了一上午。通過各種膜拜大神們的資料,總算最後有了一個還算看的過去的解決方案,來記錄一下。

頁麵中,<input type="file">控件的默認顯示

在Chrome中是這樣:screenshot
在IE裏是這樣:screenshot

要如何使它變成下麵這樣,點擊此區域也能上傳文件呢?
screenshot

原理:將input放進一個具有背景的div標簽中,並且使input透明。

html代碼:

<div ><input type="file"></div>

css代碼:

.inputbg{
    background: url(bg.jpg) no-repeat;
    position: relative;
    width: 311px;
    height: 162px;
}
.inputbg input{
    position: absolute;
    top: 0;
    left: 0;
    opacity:0;
    filter:alpha(opacity=0);
    width: 311px;
    height: 162px;
    cursor: pointer;
}
</style>

這個時候瀏覽器裏顯示是這樣的。

screenshot

看起來正常,但是功能上確有問題。

chrome:能夠實現點擊彈出文件窗口,但是在某些地方鼠標懸停的時候是 小手狀,某些地方卻是箭頭。

IE:雖然整個區域顯示都是小手狀,但是點擊會出現豎線光標。而且IE10-IE6裏都隻有一小部分區域點擊的時候會出現文件窗口,其他地方點擊沒有反應。

問題1:去掉IE瀏覽器裏的豎線光標。

在html代碼裏給input添加屬性unselectable="on"。此時,html代碼變為:

<div ><input type="file" unselectable="on"></div>

問題2:解決Chrome瀏覽器裏部分區域鼠標懸停是箭頭的問題。

添加font-size: 0;此時css代碼變為:

.inputbg{
    background: url(bg.jpg) no-repeat;
    position: relative;
    width: 311px;
    height: 162px;
}
.inputbg input{
    position: absolute;
    top: 0;
    left: 0;
    opacity:0;
    filter:alpha(opacity=0);
    width: 311px;
    height: 162px;
    cursor: pointer;
    font-size: 0;
}
</style>

問題3:解決IE10-IE6裏隻有一小部分區域點擊的時候會出現文件窗口,其他地方點擊沒有反應的問題。

這個時候會發現,如果將font-size的值設置的足夠大,就能解決這個問題。但是會影響Chrome裏的功能。所以可以針對IE10-IE6專門設置。在css添加屬性font-size: 150px\9;。現在css代碼變為

.inputbg{
    background: url(bg.jpg) no-repeat;
    position: relative;
    width: 311px;
    height: 162px;
}
.inputbg input{
    position: absolute;
    top: 0;
    left: 0;
    opacity:0;
    filter:alpha(opacity=0);
    width: 311px;
    height: 162px;
    cursor: pointer;
    font-size: 0;
    font-size: 150px\9;
}
</style>

到現在為止所有瀏覽器都顯示正常了。附上完整代碼:

html代碼:

<div ><input type="file" unselectable="on"></div>

css代碼:

.inputbg{
    background: url(bg.jpg) no-repeat;
    position: relative;
    width: 311px;
    height: 162px;
}
.inputbg input{
    position: absolute;
    top: 0;
    left: 0;
    opacity:0;
    filter:alpha(opacity=0);
    width: 311px;
    height: 162px;
    cursor: pointer;
    font-size: 0;
    font-size: 150px\9;
}
</style>

PS:之前看很多網上的其他資料發現,有的大神在定位的時候,用的是right: 0;還沒理解是什麼意思~所以還請大家多多指教~

最後更新:2017-08-14 15:02:19

  上一篇:go  SmarteamV5R16的數據庫分析(表、字段的意義)
  下一篇:go  雲服務器 ECS 配置:Linux升級時不升級內核的配置說明