【JavaScript】拖拽圖片檔案顯示縮圖 + div點選模擬 input[type=file]

走馬勿觀花發表於2020-12-06
傳送門:
1. JavaScript 教程 / 瀏覽器模型 / ArrayBuffer 物件,Blob 物件
2. HTML5 - 通過拖拽讀取圖片檔案(將電腦中圖片拖入瀏覽器並顯示)
3. js實現file上傳圖片在div中顯示與點選div觸發file表單
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<style type="text/css">
		.dropArea {
			margin: 0 auto;
			width: 600px;
			height: 300px;
			text-align: center;
			line-height: 300px;
			font-size: 2em;
			font-weight: bold;
			color: gray;
			border: 5px dashed gray;
			background-color: #e6e6e6;
			overflow: hidden;
			cursor: pointer;
		}
	</style>
</head>
<body>
	<div class="dropArea">
		<span>拖放區..</span>
		<input type="file" accept="image/*" multiple style="display: none;" "/>
	</div>
	<div class="thumbnail"></div>
	<script type="text/javascript">
		const dropArea = document.querySelector('.dropArea');
		const thumbnail = document.querySelector('.thumbnail');
		const file = document.querySelector('input[type="file"]');

		function ignoreDrag(e) {
			e.preventDefault();	// 取消預設行為
			// e.stopPropagation();	// 阻止冒泡
		}

		function fileinfo() {
			file.onchange = function() {
				dropArea.innerHTML = null;
				for (var i = 0; i < this.files.length; i++) {
					var img = document.createElement('img');
					img.src = window.URL.createObjectURL(this.files[i]);	// 記憶體生成 URL 例項
					img.width = 600;
					dropArea.appendChild(img);
					img.onload = function() {	// 圖片載入完後釋放例項,節省記憶體
						window.URL.revokeObjectURL(this.src);
					}
				}
			}
		}

		dropArea.addEventListener('dragenter', ignoreDrag, false);
		dropArea.addEventListener('dragover', ignoreDrag, false);
		dropArea.addEventListener('drop', function(e) {
			ignoreDrag(e);
			var files = e.dataTransfer.files;
			for (var i = 0; i < files.length; i++) {
				var type = files[i].type;
				if (type.substring(0, 6) !== 'image/') continue;
				var img = document.createElement('img');
				img.src = URL.createObjectURL(files[i]);
				img.onload = function() {
					this.width = 100;
					thumbnail.appendChild(this);
					URL.revokeObjectURL(this.src);
				}
			}
		}, false);
		dropArea.addEventListener('click', function(e) {
			// file模擬input點選事件
			var evt = new MouseEvent('click', {
				bubbles: false,
				cancelable: true,
				view: window
			});
			file.dispatchEvent(evt, fileinfo());
		}, false);
	</script>
</body>
</html>

相關文章