js头像(图片)上传,立即展示!——李帅醒博客

版权声明:本文为博主 我吃酸萝卜/李帅醒 原创, 未经博主允许不得转载。新浪微博@我吃酸萝卜 https://blog.csdn.net/wcslb/article/details/53589616

实现图片、或者头像的上传,并且本地浏览,今天我们就要用到H5新的Web API 接口FileReader

 IE10以下的版本不支持FileReader()构造函数.不过可以利用滤镜来兼容旧版本的IE:兼容IE的图片本地预览。


CSS代码:

<style>
	.box1{
		width: 200px;
		height: 40px;
		border-radius: 4px;
		border: 2px dashed red;
		line-height: 40px;
		margin: 0px auto;
		background: greenyellow;
		margin-bottom: 20px;
	}
	.box2{
		width: 300px;
		height: 300px;
		border: 1px solid red;
		margin: 0px auto;
		border-radius: 50%;
		background-size:cover;
		margin-top: 0px;
	}
</style>
HTML页面代码:
<body>
	<div class="box1">
		点击或拖动图片文件到此处
	</div>
	<!-- 设置一个隐藏文件上传框 -->
	<input type="file" hidden>
	<div class="box2"></div>
</body>
JS代码:

<script type="text/javascript">
	var box1=document.querySelector(".box1");
	var box2=document.querySelector(".box2");
	var input=document.querySelector("input");
	console.log(input)
	input.onchange=function(){
		fileHandler(this.files)
	}
	//当点击上传调用隐藏input标签
	box1.onclick=function(){
		input.click();
	}
	// 在元素正在拖动到放置目标时触发的事件
	box1.ondragover=function(e){
		// 终止浏览器默认事件
		e.preventDefault();
	}
	// 释放目标时触发的事件
	box1.ondrop=function(e){
		e.preventDefault();
		var files=e.dataTransfer.files;
		fileHandler(files);
	}
	function fileHandler(files){
		// files可以是多个文件,是个数组
		var file=files[0];
		// FileReader()构造函数,创建了FileReader接口
		var fd=new FileReader();
		// 将文件读取为DataURL
		fd.readAsDataURL(file);
		fd.onload=function(){
			console.log("aa")
			box2.style.backgroundImage="url("+this.result+")";
		}
	}
</script>
(我吃酸萝卜 新浪微博http://www.weibo.com/wcslb          ---李帅醒著)

猜你喜欢

转载自blog.csdn.net/wcslb/article/details/53589616