一般來說,上傳控件不是用flash做就是用input[type=file]元素了,但flash在IPAD上沒救了,而input[type=file]在各種瀏覽器中又長得不是一個樣子,因此已經我們需要用CSS來處理一下。聽說webkit可以用-webkit-appearance:none;清除默認樣式,就可以讓你為所欲為了。但天朝的炮灰們(有些公司喜歡稱我們為前端攻城師,那豈不就是炮灰吧,每改一次設計就爛頭焦額,半死不活),是用不起這么高級的東東,我們還要兼容IE6呢。最后問群里的大大,找到解決方案。
原理大致如下,既然原來的input[type=file]元素很難看就讓它消失吧。這里的消失是讓它其透明化,並在外面為其包一層,那個父元素相對定位。然后在里面添加一個DIV元素鋪底,它與input[type=file]元素是兄弟,但它是絕對定位向左對齊,層級為1,input[type=file]元素是絕對定位向右對齊,層級為3。那個DIV里面再加一個input[type=text]元素,用來冒充input[type=file],我們可以對它做各種美化。好了,現在是模擬原來上傳控件的瀏覽按鈕的時候了。讓那個DIV也變成一個定位元素,里面放個DIV或IMG什么,這個元素我姑且稱之為偽上傳按鈕吧。偽上傳按鈕絕對定位向右對齊,層級為2。當用戶點擊它時,其實是點中那個透明化了的input[type=file]元素。最后是交互部分,默認選中上傳文件后,此文件的路徑會出現在input里面的,我們搞一個onchange事件,將input[type=file]的value值賦給input[type=text]就行了。
下面是HTML部分
<div id="file_wrapper"> <div id="file_faker"> <input /> <div id="file_btn"> 瀏 覽 </div> <span class="ctr"></span> <span class="cbr"></span> <!-- 隱藏真正的上傳 --> </div> <input type="file" id="file_uploader" /> </div>
CSS部分
#file_wrapper { position: relative; width:200px; height:20px; display:inline-block; } #file_faker { position: absolute; top: 0px; left: 0px; z-index: 1; } /* 這是用戶看到的按鈕*/ #file_faker input{ width:200px; height:18px; } /* 這里是按鈕*/ #file_btn { position:absolute; top:0; right:0; width:60px; height:20px; line-height:20px; text-align :center; background:#878787; color:#fff; z-index: 2; } #file_uploader { position: relative; text-align: right; -moz-opacity:0 ; filter:alpha(opacity: 0); opacity: 0; z-index: 3; } /* 模擬圓角 */ .ctr,.cbr{ position:absolute; background:#fff; width:1px; height:1px; display:block; z-index:4; } .ctr{ top:0px; right:0px; } .cbr{ bottom:0px; right:0px; }
JS交互部分
window.onload = function(){ var $= function (id) { return "string" == typeof id ? document.getElementById(id) : id; }; $("file_uploader").onchange = function(){ $("text_box").value = this.value; } }