2011-12-02 15 views
16

可能重複:
jQuery : simulating a click on a <input type=「file」 /> doesn't work in Firefox?沒有輸入欄的文件上傳按鈕?

是否有可能有一個文件的一個按鈕默認情況下它旁邊的輸入?理想情況下,我想要的只是一個按鈕,它允許用戶導航到文件,而不顯示上傳前選擇的內容。用戶選擇文件後,我會通過下面的提交表單:

$("#file").change(function() { 
    $("#update_button").trigger('click'); 
}); 

我敢肯定,這必須有可能與一些CSS或jQuery的魔術......

回答

21

如果我沒有記錯,HTML5允許你在一個隱藏的輸入元素上調用click方法來通過一個自定義按鈕顯示文件對話框(爲什麼不只是讓它在沒有元素的情況下工作,我不知道)。不幸的是,並不是所有目前正在使用的瀏覽器都支持這個功能,所以你不能將樣式文件輸入看作是一個按鈕。

這是一個歡快的醜陋,但巧妙的CSS破解我碰上了一個網站一次(大概imgur):

.fileupload { 
    width: 100px; 
    height: 50px; 
    position: relative; 
    overflow: hidden; 
    background: ...; /* and other things to make it pretty */ 
} 

.fileupload input { 
    position: absolute; 
    top: 0; 
    right: 0; /* not left, because only the right part of the input seems to 
       be clickable in some browser I can't remember */ 
    cursor: pointer; 
    opacity: 0.0; 
    filter: alpha(opacity=0); /* and all the other old opacity stuff you 
           want to support */ 
    font-size: 300px; /* wtf, but apparently the most reliable way to make 
         a large part of the input clickable in most browsers */ 
    height: 200px; 
} 

和HTML去用它:

<div class="fileupload"> 
    <input type="file" /> 
    Any content here, perhaps button text 
</div> 

它做什麼它是否使文件輸入本身變得巨大(通過更改字體大小(!?))以確保它覆蓋按鈕,然後用overflow: hidden;切斷多餘的文件。這可能不適用於絕對巨大的按鈕。

+0

這是無用的,因爲在一些瀏覽器的文件名而來的按鈕之前,而在其他國家談到了。看到這裏:http://www.quirksmode.org/dom/pix/filefields.gif –

+1

@Dbugger:IIRC Safari允許你點擊文本部分,以及許多其他瀏覽器。至少IE不喜歡該領域的點擊,因此是正確的定位。我檢查了一下,這實際上是imgur.com所做的,我很確定他們是一個相當不錯的現場測試。 –

+0

看來,這些例子中的大多數與舊瀏覽器的例外工作...意味着IE 8和以下 – Paul

44

你可以簡單地用visibility: hidden;隱藏input按鈕,並附加一個單擊事件處理程序的其他按鈕:

HTML:

<input type="file" name="somename" size="chars"> 
<button>Choose File</button> 

CSS:

input { 
    display: block; 
    visibility: hidden; 
    width: 0; 
    height: 0; 
} 

JavaScript:

$('button').click(function(){ 
    $('input').click(); 
}); 

這裏的小提琴:http://jsfiddle.net/tCzuh/

+0

這似乎在Chrome和IE 9的工作很好,但沒有更老::( – Paul

+0

@保羅 - 有趣的。我沒有任何舊版本的IE安裝,但我測試了它通過更改瀏覽器模式爲IE7,它的工作! ?! –

+0

有趣...也許IE測試工作不正常(我不會驚訝)我會在這裏嘗試一樣。謝謝! – Paul

7

如果設置不透明度爲0,那麼你可以在它下面添加另一個div,看起來像一個按鈕。你可以用任何你喜歡的方式來設計風格。

下面工作的代碼示例:

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script> 

<div class="wrapper"> 
    <div class="fakeuploadbutton">upload</div> 
    <input id="file" type="file" name="file" /> 
</div> 
<script type="text/javascript" charset="utf-8"> 
    jQuery('#file').css('opacity',0);  
</script> 
<style type="text/css" media="screen"> 
    .wrapper { position: relative; } 
    .fakeuploadbutton { 
     background: red url('myuploadbutton.png') no-repeat top left; 
     width: 100px; height: 30px; 
    } 
    #file { 
     position: absolute; 
     top: 0px; left: 0px; 
     width: 100px; height: 30px; 
    } 
</style> 
+2

這是跨瀏覽器兼容性問題的最佳方法。 –

相關問題