头像(图片)选择器组件 简单美化改造 记录

          #pic{
			   position: absolute;
			   top: 0;
			   bottom: 0;right: 0;left: 0;
			   z-index: 10;display: none;
			   width: 1.5rem;
			   height: 1.5rem;border-radius: 0.06rpx;
			   }
			.upload-box{
				width: 1.5rem;
				height: 1.5rem;
				border-radius: 0.06rem;
				background-color: #f2f2f2;
				display: flex;flex-direction: column;
				justify-content: center;align-items: center;position: relative;overflow: hidden;
			}
			.upload-box .add-icon{
				width: 0.5rem;
				height: 0.5rem;
			}
			.upload-box .add-text{
				margin-top: 0.1rem;
				font-size: 0.24rem;color: #808080;
			}
<div class="upload-box" onclick="onChoseImg()">
	<input class="upload" id="upload" type="file" accept="image/*" title="" />
	<img src="./image/add.png" class="add-icon" />
	<span class="add-text">添加图片</span>
	<img id="pic" />					
</div>
<script>
		window.onload = function() {
			
           var input = document.getElementById("upload");

			//监听选择图片
			input.addEventListener("change", function() {
				if (input.files && input.files.length > 0) {
					var imgPath = getObjectURL(input.files[0]);
					var imgEl = document.getElementById("pic")
					imgEl.src = imgPath;//预览图片
					imgEl.style.display = "inline-block";
				
				}
			})


		}

		//获取本地图片url
		function getObjectURL(file) {
			var url = null;
			if (window.createObjectURL != undefined) {
				url = window.createObjectURL(file);
			} else if (window.URL != undefined) {
				url = window.URL.createObjectURL(file);
			} else if (window.webkitURL != undefined) {
				url = window.webkitURL.createObjectURL(file);
			}
			return url;
		}

	//选择本地图片
		function onChoseImg() {
			var input = document.getElementById("upload");
			input.click(); //模拟点击
		}

	//提交并上传图片
		function sumbit() {
			var formData = new FormData();
			formData.append("file", document.getElementById("upload").files[0]);
			$.ajax({
				type: "post",
				dataType: "json",
				url: "https://xxxxxx.....",
				data:formData,
				processData: false,
				contentType: false,
				success: function(data) {
					
				}
			})
		}

	</script>

样式如下:

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值