你如何风格输入类型=“文件”按钮?
<输入类型=“文件” />
你如何风格输入类型=“文件”按钮?
<输入类型=“文件” />
当前回答
CSS在这里可以做很多事情…耍点小花招……
<div id='wrapper'>
<input type='file' id='browse'>
</div>
<style>
#wrapper {
width: 93px; /*play with this value */
height: 28px; /*play with this value */
background: url('browseBtn.png') 0 0 no-repeat;
border:none;
overflow:hidden;
}
#browse{
margin-left:-145px; /*play with this value */
opacity:0; /* set to .5 or something so you can better position it as an overlay then back to zero again after you're done */
-ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";
filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=0);
}
</style>
::参考::http://site-o-matic.net/?viewpost=19
修道院
其他回答
你不需要JavaScript !下面是一个跨浏览器的解决方案:
请看这个例子!-适用于Chrome/FF/IE - (IE10/9/8/7)
最好的方法是将一个带有for属性的自定义标签元素附加到隐藏的文件输入元素。(标签的for属性必须匹配文件元素的id,这样才能工作)。
<label for="file-upload" class="custom-file-upload">
Custom Upload
</label>
<input id="file-upload" type="file"/>
作为一种替代方法,你也可以直接用标签包装文件输入元素:
<label class="custom-file-upload">
<input type="file"/>
Custom Upload
</label>
在样式方面,只需使用属性选择器隐藏输入元素。
input[type="file"] {
display: none;
}
然后,您所需要做的就是设置自定义标签元素的样式。(例子)。
.custom-file-upload {
border: 1px solid #ccc;
display: inline-block;
padding: 6px 12px;
cursor: pointer;
}
1 -值得注意的是,如果你使用display: none隐藏元素,它将在IE8及以下版本中不起作用。还要注意,jQuery验证默认情况下不验证隐藏字段。如果这两种情况对您来说是一个问题,这里有两种不同的方法来隐藏输入(1,2),在这种情况下可以工作。
这种方法为您提供了完全的灵活性!ES6 / VanillaJS!
html:
<input type="file" style="display:none;"></input>
<button>Upload file</button>
javascript:
document.querySelector('button').addEventListener('click', () => {
document.querySelector('input[type="file"]').click();
});
这隐藏了输入文件按钮,但实际上是从另一个普通按钮点击它,显然您可以像设置其他按钮一样设置它的样式。这是除了无用的dom节点之外没有任何缺点的唯一解决方案。多亏了display:none;,输入按钮在DOM中不保留任何可见空间。
(我已经不知道该支持谁了。但我是从Stackoverflow网站的某个地方得到这个想法的。)
这是简单的jquery。对Ryan的建议稍加修改后给出一个代码示例。
基本的html:
<div id="image_icon"></div>
<div id="filename"></div>
<input id="the_real_file_input" name="foobar" type="file">
当你准备好时,一定要在输入上设置样式:不透明度:0 你不能设置display: none,因为它需要是可点击的。但是你可以把它放在“new”按钮下面,或者如果你喜欢的话,把它塞进z-index的其他东西下面。
设置一些jquery,当你点击图像时,点击真正的输入。
$('#image_icon').click(function() {
$('#the_real_file_input').click();
});
现在你的按钮开始工作了。更改时只需剪切并粘贴值。
$('input[type=file]').bind('change', function() {
var str = "";
str = $(this).val();
$("#filename").text(str);
}).change();
发长音!您可能需要将val()解析为更有意义的内容,但您应该已经全部设置好了。
我发现了一个非常简单的方法来切换文件按钮到图片。 你只需要给图片贴上标签,然后把它放在文件按钮的顶部。
<html>
<div id="File button">
<div style="position:absolute;">
<!--This is your labeled image-->
<label for="fileButton"><img src="ImageURL"></label>
</div>
<div>
<input type="file" id="fileButton"/>
</div>
</div>
</html>
单击标记图像时,选择文件按钮。
<label>
<input type="file" />
</label>
您可以将input type="file"包装在输入的标签中。样式标签,无论你喜欢和隐藏输入display: none;