javascript input上传图片改变样式及预览图片,FileReader预览图片

DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>title>
		<style type="text/css">
		.file-ipt{position: absolute;left:0;top: 0;opacity: 0;width: 50px;height: 25px;}  //这里透明化了input框,然后绝对定位在按钮上了
		.btn{width: 50px;height: 25px; background-color: skyblue;color: white;margin-right: 80px;border: none;border-radius: 10px;font-size: 8px;}
		style>
	head>
	<body>
		<button class="btn">图片button>
		<input type="file" id="file" accept="image/jpg,imgae/jpeg,image/png" class="file-ipt" onchange="insertimg(this);"><br>
		<img src="" id="img1" alt="">
		<script language="javascript">
			function insertimg(img){
				var rd=new FileReader();
				files=img.files[0];
				var filetype=files.type.slice(6,10);
				if(filetype!='jpg'&&filetype!='jpeg'&&filetype!='png'){
					alert('仅支持png,jpeg,jpg图片格式');
					return;
				}else{
					rd.readAsDataURL(files);
					rd.onloadend=function(e){
						document.getElementById('img1').src=e.target.result;
						document.getElementById('img1').style.width="300px";
						document.getElementById('img1').style.height="auto";
					};
				}
			}
		script>
	body>
html>

你可能感兴趣的:(javascript学习日记,javascript)