在许多页面中我们都可以看到上传头像 或者上传图片 那么这些功能是怎么实现的呢?
代码如下
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<style>
.up-shang{
font-size: 20px;
color: #000;
font-weight: bold;
cursor: pointer;
}
/* css 选择器 [] 是以type=某某 或者 class=某某 进行选择 具体可看:https://blog.csdn.net/m0_64520392/article/details/129816402?spm=1001.2014.3001.5502*/
input[type=file]{
display: none !important;
/* !important 优先级 */
}
</style>
<body>
<label for="unImg" class="up-shang">点我上传图片</label>
<input type="file" id="unImg" onchange="ssss()">
<img id="jieurl" src="" alt="">
</body>
<script>
function ssss(){
// 获取input id
let unImg = document.getElementById("unImg").files[0];
//使用new FileReader 是一种异步读取文件机制
let reader = new FileReader();
//读取文件内容,结果用data:url的字符串形式表示
reader.readAsDataURL(unImg);
// 回调函数 里面传result
reader.onload = function(result){
// 获取img id
let jieurl = document.getElementById("jieurl");
console.log(result.target.result)
jieurl.src = result.target.result;
jieurl.style.display ='inline-block';
}
}
</script>
</html>
如有书写错误请指出感谢!!!