使用透明度自定义文件上传控件样式

1、在比较旧的浏览器中(比如IE9及以下,不支持 fileAPI,不支持 XMLHttprequest level2 只能用表单post文件)上传图片时,只能使用 表单 post,处于安全上的考虑,input[type="file"] 的文件选择按钮样式并不能随意修改(不过可以修改input 的透明度),可能会跟设计师的设计格格不入,这时可以使用透明效果来自定义上传按钮。

2、控件宽度最好不要超过60px,因为file控件浏览按钮的宽度无法修改,在firefox下约为60px。如果超出60px,不要设置控件的鼠标样式,由于firefox下file控件的鼠标样式只在浏览按钮上生效,如果设置鼠标样式会造成控件左边和右边样式不一致。

3、控件文字显示层的行高与控件容器层的高度保持一致以保证文字垂直居中。

4、由于安全性问题,文件上传控件必须使用鼠标点击浏览按钮弹出文件选择窗并选择文件,才能向服务器上传文件(不支持 file API ),通过js触发file控件的click() 事件来弹出文件选择窗然后选择文件的方式是无法上传文件的,因此必须使file控件覆盖在文字显示层上面,将file控件样式设置为透明来显示下面的文字层。

5、xmlhttprequest组件(level1 , level 2已经支持二进制数据上传和跨域)是无法上传文件的,异步上传文件需要使用 iframe 引入上传控件使用 表单 post 数据,可以把文件上传功能单独放在iframe内实现,也可以仅仅把处理图片上传的服务器脚本指定在iframe内打开 (设置form表单的 target 指向 iframe 窗口)。

<html>
<head>
<meta  http-equiv="content-type" content="text/html; charset=utf-8" >
<title>upload...</title>
<style>
#ui-upload-holder{ position:relative;width:60px;height:35px;border:1px solid silver; overflow:hidden;}
#ui-upload-input{ position:absolute;top:0px;right:0px;height:100%;cursor:pointer; opacity:0;filter:alpha(opacity:0);z-index:999;}
#ui-upload-txt{ position:absolute;top:0px;left:0px;width:100%;height:100%;line-height:35px;text-align:center;}

#ui-upload-filepath{ position:relative; border:1px solid silver; width:150px; height:35px; overflow:hidden;  float:left;}
#ui-upload-filepathtxt{ position:absolute; top:0px;left:0px; width:100%;height:35px; border:0px; line-height:35px;  }

.uploadlay{margin:200px; border:1px green solid; width:300px; height:200px; padding:10px;  }
</style>
</head>

<body>
<div class="uploadlay"> 
    <div id="ui-upload-filepath">
        <input type="text" id="ui-upload-filepathtxt" class="filepathtxt" />
    </div>
    
    <div id="ui-upload-holder" >        
        <div id="ui-upload-txt">上传</div>
        <input type="file" id="ui-upload-input" name="myfile" />
    </div>
</div>
<script>
document.getElementById("ui-upload-input").onchange=function(){
    document.getElementById("ui-upload-filepathtxt").value = this.value;
}
</script>
 
</body>
</html>
 
原文地址:https://www.cnblogs.com/ecalf/p/2815018.html