Click and drag to upload pictures uploaded Case

Click and drag to upload pictures uploaded jQuery writing case

First, the code

css styles

<style type="text/css">
			.box {
				width: 300px;
				height: 300px;
				margin: auto;
				box-sizing: border-box;
				position: relative;
				border: 3px dashed gainsboro;
			}

			.Original_img {
				width: 295px;
				height: 295px;
			}

			#sel_file {
				width: 300px;
				height: 300px;
				position: absolute;
				left: 0;
				top: 0;
				z-index: 2;
				opacity: 0;
			}
			h2{
				text-align: center;
			}
		</style>

body content:

<body>
		<h2>点击或者拖拽上传</h2>
		<div class="box">
			<img src="img/upload.png" class="Original_img" />
			<input type="file" id="sel_file" value="选择文件" />
		</div>
		
	</body>

js introduction portion and a jquery

<script src="js/jquery-2.1.0.js" type="text/javascript" charset="utf-8"></script>
	<script type="text/javascript">
		var sel_file = document.querySelector("#sel_file");
		var Original_img = document.querySelector(".Original_img");
		sel_file.onchange = function(e) {
			var newimg = e.target.files[0];
			upimg(newimg);
		}
		//拖拽上传
		var imgbox = document.querySelector(".box");
		//拖拽元素在在放置区域移动
		imgbox.ondragover = function() {
			return false;
		}
		imgbox.ondrop = function(e) {
			upimg(e.dataTransfer.files[0])
			return false;
		}
		//封装函数
		function upimg(newimg) {
			//实例化文件对象(构造函数)
			var fileReader = new FileReader();
			fileReader.readAsDataURL(newimg)
			fileReader.onload = function(e) {
				//把加号替换成上传图片的路径
				Original_img.src = e.target.result;
				Original_img.style.width = "295px";
				Original_img.style.height = "295px";
			}
		}
	</script>

Second, the final results are as follows:

The effect of a:

Here Insert Picture Description

Here Insert Picture Description
Here Insert Picture Description

Two results:

Here Insert Picture Description
Here Insert Picture Description
If different, welcome message corrections!

Published 18 original articles · won praise 4 · Views 570

Guess you like

Origin blog.csdn.net/weixin_45538576/article/details/103138499