html - 样式输入类型文件?

标签 html css file input cross-browser

<分区>

是否可以在不担心浏览器兼容性的情况下设置文件类型的输入元素的样式?在我的例子中,我需要实现一个背景图像和圆形边框(1px),如果可能的话还应该自定义按钮。

最佳答案

按照以下步骤,您可以为文件上传表单创建自定义样式:

1.) 这是简单的 HTML 表单(请阅读我在下面写的 HTML 注释)

    <form action="#type your action here" method="POST" enctype="multipart/form-data">
    <div id="yourBtn" style="height: 50px; width: 100px;border: 1px dashed #BBB; cursor:pointer;" onclick="getFile()">Click to upload!</div>
    <!-- this is your file input tag, so i hide it!-->
    <div style='height: 0px;width: 0px; overflow:hidden;'><input id="upfile" type="file" value="upload"/></div>
    <!-- here you can have file submit button or you can write a simple script to upload the file automatically-->
    <input type="submit" value='submit' >
    </form>

2.) 然后使用这个简单的脚本将点击事件传递给文件输入标签。

    function getFile(){
        document.getElementById("upfile").click();
    }

现在您可以使用任何类型的样式,而不必担心如何更改默认样式。 我很清楚这一点,因为我已经尝试更改默认样式一个半月了。相信我这很难,因为不同的浏览器有不同的上传输入标签。所以使用这个来构建您的自定义文件上传表单。这是完整的自动上传代码。

<html>
<style>
#yourBtn{
   position: relative;
   top: 150px;
   font-family: calibri;
   width: 150px;
   padding: 10px;
   -webkit-border-radius: 5px;
   -moz-border-radius: 5px;
   border: 1px dashed #BBB; 
   text-align: center;
   background-color: #DDD;
   cursor:pointer;
  }
</style>
<script type="text/javascript">
 function getFile(){
   document.getElementById("upfile").click();
 }
 function sub(obj){
    var file = obj.value;
    var fileName = file.split("\\");
    document.getElementById("yourBtn").innerHTML = fileName[fileName.length-1];
    document.myForm.submit();
    event.preventDefault();
  }
</script>
<body>
<center>
<form action="#type your action here" method="POST" enctype="multipart/form-data" name="myForm">
<div id="yourBtn" onclick="getFile()">click to upload a file</div>
<!-- this is your file input tag, so i hide it!-->
<!-- i used the onchange event to fire the form submission-->
<div style='height: 0px; width: 0px;overflow:hidden;'><input id="upfile" type="file" value="upload" onchange="sub(this)"/></div>
<!-- here you can have file submit button or you can write a simple script to upload the file automatically-->
<!-- <input type="submit" value='submit' > -->
</form>
</center>
</body>
</html>

关于html - 样式输入类型文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4909228/

相关文章:

css - 为 SVG 路径的一部分着色

file - 如果存在同名文件夹,则无法创建文件

jquery - Portlet 仅在 IE7 中正确关闭

html - 如何修复悬停时不显示的自定义光标

javascript - Bootstrap modal ('hide' ) 没有删除所有应用的属性

html - 想要 CSS 属性 : line separator above heading

ios - 显示文件大小 : 1000b = 1kb or 1024b = 1kb?

css - 无法使用 .htaccess 中的 RewriteRule 访问文件

javascript - 不同设备上两个不同HTML文件之间的通信(JS)

html - 嵌套 CSS 覆盖元素类