2013-05-01 81 views
2

這是我的代碼:跨瀏覽器的造型 「選擇文件」 按鈕

HTML:

<form> 
    <input id = "file" type="file" /> 

    <div id="custom_button">custom button</div> 
</form> 

的Jquery:

$("#custom_button").on("click", function() { 
    $("#file").click();  
}); 

CSS:

#file { 
    display: none; 
} 

但這個作品只有在Firefox和鉻,在safari和歌劇,在clic鉀對custom button,窗口文件選擇並沒有叫

DEMO:http://jsfiddle.net/J4GdN/

Qusetion:爲什麼這不是在Safari和Opera的作品?什麼是替代方案,在這些瀏覽器中做到這一點?

+0

它適用於我在Safari上。 – undefined 2013-05-01 11:39:46

+2

http://stackoverflow.com/questions/210643/in-javascript-can-i-make-a-click-event-fire-programmatically-for-a-file-input – dt192 2013-05-01 11:44:41

+2

http://stackoverflow.com/questions/12035400/how-can-i-remove-the-no-file-chosen-tooltip-from-a-file-input-in-chrome – undefined 2013-05-01 11:45:33

回答

1

某些用戶代理不允許通過js觸發點擊輸入文件元素,特別是在css display:none中。另一種方法是這樣:

HTML

<input id="file-element" type="file" name="my-file-upload" /> 
<div id="file-element-replacement"> 
    <input type="text" value="" /> 
    <img alt="custom upload" src="custom-upload.png" /> 
</div> 

CSS

#file-element { 
    /* if opacity is 0 => some UAs interpret it like display:none */ 
    filter: alpha(opacity=1); 
    filter: progid:DXImageTransform.Microsoft.Alpha(opacity=1); 
    -moz-opacity: 0.01; 
    -webkit-opacity: 0.01; 
    opacity: 0.01; 
    position: relative; 
    z-index: 2; 
} 

#file-element-replacement { 
    position: relative; 
    top: -20px; 
    z-index: 1; 
} 

讓你的輸入文件tranparent並有輸入文字+圖像背後的一層模擬此。

0

另一種選擇是使用標準<label>標籤,設置for屬性的<input>id

然後,您可以隱藏<input>並根據需要設置<label>的樣式。

在我的測試中,這在跨瀏覽器的情況下非常有效,因爲它是標準功能。

+0

好吧,Mamuz有個更好的主意。在許多瀏覽器中,將焦點移動到目標元素上,但不會響應或將其他事件傳遞給按鈕(在某些瀏覽器中,就像在UI中,QT默認與GTK不一樣)。如果您將標籤移動到按鈕的下方,您可以做@Mamuz所做的,只用標籤替換div(更優雅)。我仍然希望有一個選擇器來自己按鈕... – cox 2013-05-11 17:19:58