input[type=file]样式更改以及图片上传预览


  以前知道input[type=file]可以上传文件,但是没用过,今天初次用,总感觉默认样式怪怪的,想修改一下,于是折腾了半天,总算是小有收获。

  

  以上是默认样式,这里我想小小的修改下:

  HTML代码如下:

<form action="" name="file" class="file">
    上传文件<input type="file" id="img" name="img">
</form>

  

  css代码如下:

<style>
    .file{
	width: 75px;
        height: 25px;
	line-height: 25px;
	text-align: center;
	background-color: green;
	position:relative;
    }
    .file input{
	width: 75px;
        height: 25px;
	opacity:0;
	filter:alpha(opacity=0);
	position:absolute;
	left:0;
	top:0;
    }
</style>        

  

  更改后,效果如下(样式很丑,这里主要是阐述下怎么更改input[type=file]默认样式的)

  

 

  下面来说下使用input[type=file]上传图片实现预览效果的。

  

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<style>
		.file{
		   width: 75px;
		    height: 25px;
		    line-height: 25px;
		    text-align: center;
		   background-color: green;
		   position:relative;
		}
		.file input{
		   width: 75px;
		    height: 25px;
		   opacity:0;
		   filter:alpha(opacity=0);
		   position:absolute;
		   left:0;
		   top:0;
		}
	</style>
</head>
<body>
	<form action="" name="file" class="file">
		上传文件
		<input type="file" id="img" name="img">
	</form>
	<div id="dd"></div>
	<script>
		var file = document.getElementById("img");
		file.onchange = function(){  // 文本框内容改变时触发
			var files = this.files; // 获取文件的数量
			for(var i=0;i<files.length;i++){
				readers(files[i])
			}
		}
		function readers(fil){
			var reader = new FileReader();  // 异步读取存储在用户计算机上的文件
			reader.readAsDataURL(fil); // 开始读取指定的Blob对象或File对象中的内容
			reader.onload = function(){
				document.getElementById("dd").innerHTML += "<img src='"+reader.result+"'>";  // 添加图片到指定容器中
			}; 
		}
	</script>
</body>
</html>

  

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM