举个栗子,鼠标悬停头像位置呼出浮层,点击浮层按钮可修改头像。
不说废话,直接看效果图:
图1 正常情况下 图2 鼠标悬停于头像位置时
html代码:
<div class="user-avatar">
<img id="headUrl">
<div class="modify-avatar">
<form encType="multipart/form-data" id="js-upload">
<span>修改头像</span>
<input id="upload-img" class="file" type="file" name="img"/>
</form>
</div>
</div>
scss代码:
.user-avatar{
position: relative;
width: 120px;
height: 120px;
margin: auto;
&:hover .modify-avatar{
opacity: 1;
}
.modify-avatar{
position: absolute;
width: 120px;
height: 120px;
-webkit-border-radius: 60px;
-moz-border-radius: 60px;
border-radius: 60px;
top: 0;
left: 0;
background-color: rgba(0,0,0,0.5);
font-size: 14px;
color: #fff;
z-index: 888;
opacity: 0;
span{
position: absolute;
left: 32px;
top: 55px;
cursor: pointer;
}
.file{
position: absolute;
display: block;
width: 55px;
height: 18px;
left: 32px;
top: 55px;
opacity: 0;
filter:alpha(opacity=0);
}
}
img{
width: 120px;
height: 120px;
-webkit-border-radius: 60px;
-moz-border-radius: 60px;
border-radius: 60px;
}
}
js代码:
注:进入该页面时,从接口获取用户头像地址并显示头像
$("#headUrl").attr('src','//'+data.headUrl); //用户头像
postEditUserInfo();//点击表单“提交”按钮,调用此函数
/**
* 判断是否是img
* @param {*} target
*/
function isImage(target) {
if(typeof FileReader != 'undefined') {
const file = target.files[0] || {}, type = file.type || '', reg = /image\/jpg|jpeg|png/i;
if(!reg.test(type)) {
return false;
}
}else {
const fileName = target.value,
suffixIndex = fileName.lastIndexOf('.'),
suffix = fileName.substring(suffixIndex + 1).toUpperCase(),
reg = /jpg|jpeg|png/i;
if(!reg.test(suffix)) {
return false;
}
}
return true;
}
/**
* 提交表单
*/
function postEditUserInfo(){
var imgUrl,_this = this;
$("#upload-img").change(function(){//上传头像
const $form = $("#js-upload");
if(_this.isImage(this)) {
$form.ajaxSubmit({
url: API.uploadimg,
type: 'post',
dataType: 'json',
success: function(json) {
if(json.success && json.result) {
imgUrl = json.result.url;
$("#headUrl").attr('src','//'+imgUrl);//用户头像
}else {
Util.alertMessage(json.error || json.errorMessage);
}
},
error:function(){
Util.alertMessage('上传失败')
}
});
}else {
$("#js-upload").get(0).reset();
Util.alertMessage('请上传图片(支持jpg、png)');
}
});
//省略不相关代码 ......
}
版权声明:本文为博主原创文章,未经博主允许不得转载。https://blog.csdn.net/qq_36584352/article/details/80527181