鉴于文件域在名浏览器中的不同表现
应公司项目需求,用js模拟了一个文件域input type= file
代码如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<style type="text/css">
* { margin:0; padding:0;}
form { width:340px; margin:100px auto; font-size:12px; background:#444; padding:20px; color:#fff;}
form p label { display:block;}
#inputFile { display:block; background:url(fileBg.jpg) no-repeat 0 0; width:339px; height:28px; overflow:hidden; margin-top:5px;position:relative; cursor:pointer;}
#inputFile.over { background-position:0 -28px;}
#inputFile input {font-size:21px;filter: Alpha(Opacity=0);opacity:0; position:absolute; z-index:10; color:#fff; cursor:pointer;}
#fileName { position:absolute; z-index:9;width:260px; height:20px;display:block; margin:5px;z-index:1; font-family:Arial, Helvetica, sans-serif; font-size:14px; color:#333; cursor:pointer;}
</style>
</head>
<script type="text/javascript">
window.onload = function(){
var inputFile = document.getElementById('inputFile');
var fileName = document.getElementById('fileName');
var fileUpload = document.getElementById('fileField');
inputFile.onmouseover = function(){
this.className = 'over';
}
inputFile.onmouseout = function(){
this.className = '';
}
fileUpload.onchange = function(){
/*在IE里文件域的值会包含文件咱径,所以在这里需要截取最后部份的文件名*/
var index = this.value.lastIndexOf("\\");
if(index != -1){
var str = this.value.substr(index+1);
fileName.innerHTML = str;
}else{
/*如果不包含文件路径,则直接将input的值显示出来*/
fileName.innerHTML = this.value;
}
}
}
</script>
<body>
<form action="" method="get">
<p><label for="fileField">文件上传</label>
<span id="inputFile"><span id="fileName"></span>
<input type="file" name="fileField" id="fileField"/>
</span></p>
</form>
</body>
</html>
素材图片:
(责任编辑:apple)