saber 酱的抱枕

Fly me to the moon

09/5
2015
学习

修改表单中file控件的外观

表单中的file上传控件在各个浏览器中的外观都不太一样,所以我们可以自己做一个外观。原理是隐藏file控件,然后自己做出文件名的显示区域,以及选择按钮。

<form id="form0">
	<input type="file" id="fileinput1">
	<span id="showfile">尚未选择文件</span>
	<span title="选择文件" id="selectbtn1">选择文件</span>
	<span class="tip">图片必须为jpg格式,体积小于2M,文件名不能包含“sox”三个字</span>
</form>
<style>
	#fileinput1{display: none;}
	#form0 span{border-radius: 5px;font-family: '微软雅黑';display: inline-block;}
	#showfile{width: 300px;height: 34px;line-height: 34px;color: #aaa;padding:0 5px 0 10px;border:1px solid #0c0;white-space:nowrap;  text-overflow:ellipsis;overflow: hidden;vertical-align:top;}
	#selectbtn1{width: 100px;height: 36px;line-height: 36px;background:#4DB849;color: #fff;text-align: center;cursor: pointer;vertical-align:top;}
	.tip{margin-left: 5px;color: #aaa;height: 36px;line-height: 44px;}
</style>
<script>
	document.getElementById("selectbtn1").onclick=function  () {
		document.getElementById("fileinput1").click();
	}
	document.getElementById("fileinput1").onchange=function(){
		if (this.files[0].type!="image/jpeg") {
			alert("文件格式不正确!");
			return false;
		}else if(this.files[0].size>2000000){
			alert("文件体积过大!");
			return false;
		}else if (this.files[0].name.toLowerCase().indexOf("sox")>-1) {
			alert("文件名包含非法字符!");
			return false;
		};
		document.getElementById("showfile").innerHTML=this.files[0].name;//这里没有用value,因为获取不到真实的绝对路径的,不如只显示文件名
		document.getElementById("showfile").style.color="#333";
	}
</script>

点击选择文件按钮的时候用js去触发file控件;在选取文件之后,将文件信息显示到文件名区域里。

你可能会注意到files[]这个集合:

this.files[0]

这是html5中为file控件增加的属性,通用的有name、size、type、lastModified这几个属性。这些属性可以用来对上传的文件做一些检测。

注意,size的单位是Byte(字节)。

修改表单中file控件的外观

评论 locationiskey 撤销评论