1. 程式人生 > >圖片上傳預覽的簡單程式碼

圖片上傳預覽的簡單程式碼

效果如下圖
在這裡插入圖片描述
程式碼如下:


<!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>