【问题标题】:Cross browser styling "choose file" button跨浏览器样式“选择文件”按钮
【发布时间】:2013-04-25 09:43:00
【问题描述】:

这是我的代码:

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 和 chrome,在 safari 和 opera 中,点击custom button,文件选择窗口没有调用

演示:http://jsfiddle.net/J4GdN/

问题:为什么这在 safari 和歌剧中不起作用?在这些浏览器中进行此操作的替代方法是什么?

【问题讨论】:

标签: javascript jquery html button file-upload


【解决方案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;
}

使您的输入文件透明,并使用输入文本 + 图像作为后面的层来模拟。

【讨论】:

    【解决方案2】:

    另一种选择是使用标准的&lt;label&gt; 标签,将for 属性设置为&lt;input&gt;id

    然后您可以隐藏&lt;input&gt; 并根据需要设置&lt;label&gt; 的样式。

    在我的测试中,由于它是标准功能,因此它在浏览器中运行良好。

    【讨论】:

    • 嗯,马穆兹有个更好的主意。
    猜你喜欢
    • 2016-09-16
    • 2016-02-13
    • 2015-11-04
    • 1970-01-01
    • 1970-01-01
    • 2015-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多