使用js设置以当前用户邮箱头像作为头像

设置用户头像。当页面中包含有 classavatar 的元素时,遍历这些元素并调用函数 getEmailAvatar,并将用户的邮箱作为参数传入函数中。函数 getEmailAvatar 首先通过正则表达式判断邮箱地址的类型,然后返回对应类型的头像地址;如果不是支持的邮箱类型,则返回默认的头像地址。最后设置 src 属性为该头像地址,从而实现显示用户头像的效果。

// 获取所有拥有 'avatar' class 的元素
const avatars = document.querySelectorAll('.avatar');

// 遍历设置每个元素的头像
avatars.forEach(avatar => {
  const email = "{:$user.email}";
  const avatarUrl = getEmailAvatar(email);
  avatar.src = avatarUrl;
});

function getEmailAvatar(email) {
  // 使用正则表达式判断邮箱格式是否为 QQ 邮箱
  if (/^[1-9][0-9]{4,10}@qq\.com$/.test(email)) {
    // 如果为 QQ 邮箱,则生成 QQ 头像地址
    return `https://q1.qlogo.cn/g?b=qq&nk=${email}&s=100`;
  } else if (/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+\.[a-zA-Z0-9_-]+$/.test(email)) {
    // 如果为普通邮箱,则生成 Gravatar 头像地址
    const md5Email = md5(email.toLowerCase());
    return `https://gravatar.kuibu.net/avatar/${md5Email}?s=100`;
  } else if (/^[A-Za-z0-9][\w\.-]+[A-Za-z0-9]@163\.com$/.test(email)) {
    // 如果为 163 邮箱,则生成 163 头像地址
    const user = email.split('@')[0];
    return `https://mail.163.com/js6/s?func=mbox:getMessageList&sid=zhaohui_hedahua92&r=${Math.random()}&fid=1&user=${user}&l=100`;
  } else if (/^[A-Za-z0-9][\w\.-]+[A-Za-z0-9]@sina\.cn$/.test(email)) {
    // 如果为新浪邮件,则生成新浪头像地址
    const user = email.split('@')[0];
    return `http://my.sina.com.cn/avatar.php?uid=${user}&size=big`;
  } else {
    // 否则返回默认头像地址
    return 'https://mpay.blogcloud.cn/static/admin/images/avatar.jpg';
  }
}
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

给TA打赏
共{{data.count}}人
人已打赏
技术教程

Linux搭建GitLab

2023-5-8 15:48:43

技术教程

Linux自动同步时间脚本

2023-5-16 9:18:56

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索