jquery.fileEveryWhere.js 一個跨瀏覽器的file顯示外掛程式

來源:互聯網
上載者:User

先來看看input type="file"在chrome,ie,firefox這三個瀏覽器下表情各異吧。

 

 

 

chrome像是button+label組合,看起差異最大。

ff和ie,是text+button的組合,就外形來看,firefox更標準,事實上firefox存在兩個潛在問題:

 1,firefox對type="file" 的input的width定義目前是不支援的(但是FF支援size屬性,可以給size設定一個值,來控制上傳框的大小,至於這個size到底是多大,見文章繁花-firefox下input type="file"的size是多大)。 

 2,Firefox瀏覽器的提交file表單時只提交檔案名稱不提交路徑,而IE提交的是路徑+檔案名稱,chrome也能提交路徑+檔案名稱,但只顯示檔案名稱。Firefox瀏覽器的提交file表單時只提交檔案名稱不提交路徑(很遺憾,暫時沒有解決方案)

 

要讓file在各個瀏覽器顯示統一,純樣式已經控制不了,只能用js指令碼了。基本步驟有3:

 1,通過文字框和按鈕去類比一個input type=”file”。

 2,把input="file"做成透明,用定位完全蓋住文字框和按鈕。

 3,當input type=”file”的onchange的時,用js將文字框的值設定成input type=”file”的值。

瞭解步驟後,整個外掛程式就很好寫了,代碼如下:
複製代碼 代碼如下:
/*
* file everywhere - 瀏覽器通用檔案上傳
* copyright->flowerszhong
* flowerszhong@gmail.com
*/
(function($) {
$.fn.fileEveryWhere = function(options) {
var defaults = {
WrapWidth: 300,
WrapHeight: 30,
ButtonWidth: 60,
ButtonHeight: 28,
ButtonText: "瀏覽",
TextHeight: 28,
TextWidth: 240
};
var options = $.extend(defaults, options);
var browser_ver = $.browser.version.substr(0, 1);
var displayMode = ($.browser.msie && browser_ver <= "7") ? "inline" : "inline-block";
return this.each(function() {
//建立包含,設定為相對定位
var wrapper = $("<div class='fileWraper'>")
.css({
"width": options.WrapWidth + "px",
"height": options.WrapHeight + "px",
"display": displayMode,
"zoom": "1",
"position": "relative",
"overflow": "hidden",
"z-index":"1"
});
//建立文本輸入框,用於存放上傳檔案名稱
var text = $('<input class="filename" type="text" />')
.css({
"width": options.TextWidth + "px",
"heigth": options.TextHeight + "px"
});
//建立瀏覽按鈕
var button = $('<input class="btnfile" type="button" />')
.val(options.ButtonText);
$(this).wrap(wrapper).parent().append(text, button);
$(this).css({
"position": "absolute",
"top": "0",
"left": "0",
"z-index": "2",
"height": options.WrapHeight + "px",
"width": options.WrapWidth + "px",
"cursor": "pointer",
"opacity": "0.0",
"outline":"0",
"filter": "alpha(opacity:0)"
});
if ($.browser.mozilla) { $(this).attr("size", 1 + (options.WrapWidth - 85) / 6.5) }
$(this).bind("change", function() {
text.val($(this).val());
});
});
};
})(jQuery);

使用很簡單:

$("input:file").fileEveryWhere({參數});

這樣就可以統一顯示input="file",並且易於美化。
下載該外掛程式:jquery.fileEveryWhere.rar
來自:http://www.cnblogs.com/flowerszhong/

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.