2011-06-23 210 views
4

我一直在寻找圣杯 - 在HTML中很好的文件对话框。当我点击一个按钮时,我想出了一个解决方案,该解决方案使用jQuery到click()(隐藏)文件元素。这在FireFox 4中运行良好,但Chrome和Opera失败。将Chrome浏览器更改为click()focus(),但Opera没有任何功能。我还没有测试过IE,但我还不想让人生蛮荒。跨浏览器打开文件浏览对话框

下面是当前的代码:

HTML

<div class="formFile" id="profileImgContainer"> 
    <input type="file" name="profileImg" id="profileImg"> 

    <label>Profile Picture</label> 

    <div> 
     <input type="text" id="profileImgText"><input type="button" id="profileImgButton" value="Choose File"> 
    </div> 
</div> 

jQuery的

$(".formFile input[type='file']").live('change', function() 
{ 
    $(this).parents(".formFile").find("input[type='text']").val($(this).val()); 
}); 

$(".formFile input[type='button']").live('click', function() 
{ 
    $(this).parents(".formFile").find("input[type='file']").click(); 
}); 

$(".formFile input[type='text']").live('click', function() 
{ 
    $(this).parents(".formFile").find("input[type='file']").click(); 
}); 

谁能提供开放使用jQuery/JavaScript的文件对话框的跨浏览器的方式?我不想因使用透明元件招需要有输入交互(CSS :hover)等

+1

+1对'我不想让人生相当狂欢:-) – andyb

+0

感谢andyb。 IE是我存在的祸根。如果它进入了一个洞并死亡(或被FF,Chrome,香肠等取代),那么我和其他所有Web开发人员都会变得更加快乐! – Bojangles

+1

不能同意更多!顺便说一句,你见过http://stackoverflow.com/questions/210643/in-javascript-can-i-make-a-click-event-fire-programmatically-for-a-file-input-e/3030174#3030174 – andyb

回答

3

尝试使用trigger()

$(this).parents(".formFile").find("input[type='file']").trigger('click'); 
+0

现在FF4和Chrome运行良好,但Opera 11.11不想玩得好。有任何想法吗? – Bojangles

+0

对我来说,它从来没有工作 –

+0

@Sarah那么你一定是做错了什么... – Neal

4

这可能是一些晚年,但这里的是一种不使用任何Javascript的方式,它也是跨浏览器。

<label> 
    Open file dialog 
    <input type="file" style="display: none"> 
</label> 

如果你发现问题,则可能需要在标签指向输入的ID使用的属性。

+1

我认为这是我见过的最聪明的答案StackOverflow。 – Greg

+1

@Greg谢谢:) –