图片上传预览的简单代码

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/daxianghaoshuai/article/details/85245873

效果如下图
在这里插入图片描述
代码如下:


<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<title></title>
	</head>
	<body>
		<div id="img-pre"></div> 
		<div id="add-pic"> 
			<input type="file" id="up-file" onchange="fChange()"> 
		</div>
	</body>
	<script type="text/javascript">
		let addPic = document.getElementById('add-pic'),
			upFile = document.getElementById('up-file');
		// 监听图片点击,从而触发input file的点击事件
		addPic.addEventListener('click', function(){ 
			upFile.click(); 
		}) 
		function fChange() { 
			let file = document.getElementById('up-file'); 
			let imgPre = document.getElementById('img-pre'); 
			 
			// file 转 blob对象 
			let bold = window.URL.createObjectURL(file.files[0]); 

			// 创建img元素,并添加到img-pre元素里 
			var img = document.createElement("img"); 
			img.setAttribute("src", bold); 
			imgPre.appendChild(img); 
		}
	</script>
	<style type="text/css">
		#add-pic{ 
		    width: 100px;
			height: 100px;
			background: url(./add-pic.png) no-repeat center;
			background-size: contain;
			cursor: pointer;
		} 
		#add-pic input{ 
			 width: 100%; 
			 height: 100%; 
			 display: none; 
		} 
		#img-pre:after{ 
			 display: block; 
			 content: ''; 
			 clear: both; 
		} 
		#img-pre img{ 
			 float: left; 
			 width: 100px; 
			 height: 100px; 
			 margin-right: 10px; 
		}
	</style>
</html>

猜你喜欢

转载自blog.csdn.net/daxianghaoshuai/article/details/85245873