我正在尝试做的是添加一个用于上载文件的按钮,该按钮可以设置样式,并向我显示所选文件的名称。
我进行了很多搜索,搜索得越多,发现的解决方案就越多。我发现,您不能直接设置输入的样式,因为您不能... :(。
最后,我从每种解决方案中都选择了一点,然后得出以下结论:
我在输入[type file]的标签中设置了跨度,并通过display:none;隐藏了输入。
现在,我可以根据需要设置跨度的样式,然后单击以调用输入。在小JS末尾,获取输入的值(选择的文件的名称),并在样式按钮上显示它的跨接文本。
但看看自己:
#input-file {
display: none;
}
.upload-btn {
display: block;
text-align: center;
margin: 20px auto 20px;
width: 50%;
height: 30px;
background-color: #fcff7f;
line-height: 30px;
}
.upload-btn:hover {
background-color: #c39d5a;
color: white;
cursor: pointer;
}
<label class="upload-btn">
<input type="file" id="input-file" onchange="changeText()" />
<span id="selectedFileName">Browse</span>
</label>
<script type="text/javascript">
function changeText() {
var y = document.getElementById("input-file").value;
document.getElementById("selectedFileName").innerHTML = y;
}
</script>
我想知道的是,这有什么问题?就我的理解而言,它非常简单,如此之简单,以至于我不明白为什么“我”却无法在互联网上找到所有的解决方案。他们总是尝试使用带有不透明性等的伪造输入。
因此,请有经验的人可以告诉我是否可以这样使用它,还是必须更改它?要什么?
谢谢;),以及许多不好的英语借口。
由于安全原因,此功能在浏览器中不可用。
查看此说明:https : //stackoverflow.com/a/15201258/586051
仅Firefox浏览器允许。请在Firefox中参考以下示例。
编辑:您可以通过以下方式获取所选文件的文件名:
EDIT2:以下代码段演示了文件上传按钮的样式。在这里,我们实际上是在伪造它,但最终用户不会知道它。;)
EDIT3:fullPath
在注释中增加了的价值。
EDIT4:<div>
在HTML中添加了包装器
document.getElementById("customButton").addEventListener("click", function(){
document.getElementById("fileUpload").click(); // trigger the click of actual file upload button
});
document.getElementById("fileUpload").addEventListener("change", function(){
var fullPath = this.value; // fetched value = C:\fakepath\fileName.extension
var fileName = fullPath.split(/(\\|\/)/g).pop(); // fetch the file name
document.getElementById("fileName").innerHTML = fileName; // display the file name
}, false);
#fileUpload{
display: none; /* do not display the actual file upload button */
}
#customButton{ /* style the fake upload button */
background: yellow;
border: 1px solid red;
}
<div>
<input type="file" id="fileUpload"> <!-- actual file upload button -->
<button id="customButton">My Custom Button</button> <!-- fake file upload button which can be used for styling ;) -->
<span id="fileName"></span>
</div>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句