2012-02-26 44 views
1

HTML:如何模仿點擊文件輸入?

<div class="fileinputs"> 
    <input type="file" name="postgallery_set-0-image_0" id="id_postgallery_set-0-image_0"> 
    <div class="fakefile"> 
     <img src="/img/image_choice.png" /> 
    </div> 
</div> 

CSS:

div.fileinputs { 
      position: relative; 
     } 

     div.fakefile { 
      top: 0px; 
      left: 0px; 
      z-index: 1; 
      cursor: pointer; 
     } 

     .fileinputs input { 
      position: relative; 
      text-align: right; 
      -moz-opacity:0 ; 
      filter:alpha(opacity: 0); 
      opacity: 0; 
      z-index: 2; 
     } 

和JS:

$('.fakefile').click(function() { 
    $(this).parent().children('input').click(); 
}); 

這在Chrome和Firefox瀏覽器工作正常。
在IE8中,發生以下情況: 一切正常,但在提交表單文件輸入時被清除,表單不發送,並且光標放置在隱藏文件輸入上,如何使其在IE中工作?

回答

0

你其實不需要JS來達到這個效果。 HTML <label>只適用於這種類型的東西。例如

<div class="fileinputs"> 
    <input type="file" name="postgallery_set-0-image_0" id="id_postgallery_set-0-image_0"> 
    <label for="id_postgallery_set-0-image_0"> 
    <img src="/img/image_choice.png" /> 
    </label> 
</div> 
+0

只能在Chrome中工作,在Firefox和IE中無法正常工作 – TigorC 2012-02-26 09:33:43