在我的不少項目中,都有缺省頭像的問題。為了保持個性和方便辨認,會給沒有頭像的用戶填充帶名字的頭像。
代碼分享:https://github.com/joaner/namedavatar
調用簡單
如果上傳頭像不存在,直接會在 <img> 標簽上填充默認頭像,用戶名從alt獲?。?/p>
<img alt="李連杰" width="32" style="border-radius: 100%"><img src="./invalid.jpg" alt="Tom Hanks" width="40"><script>requirejs('namedavatar', function(namedavatar){ namedavatar.config({ nameType: 'lastName', }) namedavatar.setImgs(document.querySelectorAll('img[alt]'), 'alt')})</script>
如果<img src="./invalid.jpg">資源無效,namedavatar.setImgs()就會填充alt里的用戶名,src變成這樣
<img id="avatar1" src="data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32"><rect fill="#9C27B0" x="0" y="0" width="100%" height="100%"></rect><text fill="#FFF" x="50%" y="50%" text-anchor="middle" alignment-baseline="central" font-size="16" font-family="Verdana, Geneva, sans-serif">Hanks</text></svg>">
相比其它類似項目
也支持Vue.js的 directive 指令方式
import { directive } from 'namedavatar/vue'// register as directiveVue.directive('avatar', directive);// in vue template<template><img v-avatar="'Tom Hanks'" width="36"/></template>
以上就是本次整理的全部內容,感謝大家對武林網的支持。
新聞熱點
疑難解答