你如何风格输入类型=“文件”按钮?
<输入类型=“文件” />
你如何风格输入类型=“文件”按钮?
<输入类型=“文件” />
当前回答
最好的方法是使用伪元素:after或:before作为显化de input的元素。然后按照您的意愿设置该伪元素的样式。我建议你为所有输入文件做一个通用的样式,如下所示:
input {
height: 0px;
outline: none;
}
input[type="file"]:before {
content: "Browse";
background: #fff;
width: 100%;
height: 35px;
display: block;
text-align: left;
position: relative;
margin: 0;
margin: 0 5px;
left: -6px;
border: 1px solid #e0e0e0;
top: -1px;
line-height: 35px;
color: #b6b6b6;
padding-left: 5px;
display: block;
}
其他回答
我能想到的唯一方法是在它被渲染后用javascript找到按钮,并分配一个样式给它
你也可以看看这个记录
一个快速粗暴的方法是将标签设置为按钮,并将位置设置为绝对,这样它就会浮动在原始按钮上,你仍然可以看到文件名。不过,我正在考虑移动解决方案。
当点击有样式的<div>时,只需使用trigger()函数模拟点击<input>。我在<div>中创建了自己的按钮,然后在点击我的<div>时触发了输入上的单击。这允许你创建你想要的按钮,因为它是一个<div>,模拟点击你的文件<input>。然后在<input>上使用display: none。
// div styled as my load file button
<div id="simClick">Load from backup</div>
<input type="file" id="readFile" />
// Click function for input
$("#readFile").click(function() {
readFile();
});
// Simulate click on the input when clicking div
$("#simClick").click(function() {
$("#readFile").trigger("click");
});
如果有人仍然关心如何在没有JavaScript的情况下做到这一点,让我完成Josh的回答:
如何显示文件名的文本:
最简单的方法是将这两个元素设置到一个位置:相对,给标签一个更高的z-index,并给输入文件负边距,直到标签文本在你想要的位置。不要在输入时使用display:none !
例子:
input[type="file"] {
position:relative;
z-index:1;
margin-left:-90px;
}
.custom-file-upload {
border: 1px solid #ccc;
display: inline-block;
padding: 6px 12px;
cursor: pointer;
position:relative;
z-index:2;
background:white;
}
正如JGuo和CorySimmons提到的,您可以使用可样式标签的可点击行为,隐藏不太灵活的文件输入元素。
<!DOCTYPE html>
<html>
<head>
<title>Custom file input</title>
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
</head>
<body>
<label for="upload-file" class="btn btn-info"> Choose file... </label>
<input id="upload-file" type="file" style="display: none"
onchange="this.nextElementSibling.textContent = this.previousElementSibling.title = this.files[0].name">
<div></div>
</body>
</html>