1. 程式人生 > 實用技巧 >vue生成隨機樣式的驗證碼(噪點背景、顏色,字型樣式、大小)

vue生成隨機樣式的驗證碼(噪點背景、顏色,字型樣式、大小)

先來感受下效果圖,點選右側的驗證碼可以改變驗證碼內容和樣式

說下思路,利用vue生成隨機數,然後使用樣式表隨機生成樣式,已達到隨機生成驗證碼大小和樣式的效果

顯示驗證碼的程式碼部分

<span @click="getReCode()" class="login-code-img">
    <span :style="reOneStyle">{{reOne}}</span>
    <span :style="reTwoStyle">{{reTwo}}</span>
    <span :style="reThreeStyle">{{reThree}}</span>
    <span :style="reFourStyle">{{reFour}}</span>
</span>

用到的引數部分

//顯示的驗證碼部分,以及隨機樣式部分
reOne:"",
reTwo:"",
reThree:"",
reFour:"",
reOneStyle:"",
reTwoStyle:"",
reThreeStyle:"",
reFourStyle:"",
//全域性用來獲取驗證碼嗎的值欄位
flushReCode:"",

方法部分

//生成驗證碼(需要把獲取驗證碼的方法放到頁面載入事件裡面,保證進入頁面可以刷到驗證碼)
getReCode(){
let chars = ["0","1","2","3","4","5","6","7","8","9"];
let res = "";
for (let i = 0; i < 4; i++) {
let id = Math.ceil(Math.random() * 9);
res += chars[id];
}
this.reOne = res[0];
this.reTwo = res[1];
this.reThree = res[2];
this.reFour = res[3];
//這裡直接呼叫獲取樣式,保證驗證碼生成之後,可以直接獲取驗證碼的樣式
this.getStyle();
this.flushReCode = res;
return res.toString();
},
//隨機驗證碼樣式
getStyle(){
let chars = [
"font-weight: bold;font-size: 32px;text-decoration:overline;color:#BA55D3;font-family: 'Arabic Typesetting'",
"font-weight: bold;font-size: 26px;text-decoration:overline;color:pink;font-family: 'PingFang SC'",
"font-weight: solid;font-size: 33px;text-decoration:line-through;color:hotpink;font-family: Vijaya",
"font-weight: bold;font-size: 25px;text-decoration:underline;color:#9400D3; font-family: Aharoni",
"font-weight: bold;font-size: 29px;text-decoration:underline;color:#FF8C00;font-family: 'Arabic Typesetting'",
"font-weight: bold;font-size: 27px;text-decoration:line-through;color:#FF1493;font-family: 'PingFang SC'",
"font-weight: solid;font-size: 28px;text-decoration:line-through;color:#1E90FF;font-family: Vijaya",
];
let res = [];
for (let i = 0; i < 4; i++) {
let id = Math.ceil(Math.random() * 7);
res[i] += chars[id-1];
}
this.reOneStyle = res[0];
this.reTwoStyle = res[1];
this.reThreeStyle = res[2];
this.reFourStyle = res[3];
return res.toString();
},

背景的噪點圖片是百度得到的,我們沒有使用連結,二十直接轉化為了base64的字串,頁面可以直接解析

部分樣式展示

轉換成base64格式的圖片
圖片轉換為base64編碼的站點地址 http://tool.chinaz.com/tools/imgtobase/

這裡是驗證碼的背景部分

.login-code-img {
background-image:url(這裡填寫的是轉換後的base64編碼,會很長)
border: 1px solid #f0f0f0;
color: #333;
font-size: 14px;
font-weight: 700;
letter-spacing: 5px;
line-height: 38px;
text-indent: 5px;
text-align: center;
width: 33%;
}

然後執行專案,就可以達到想要的效果了,樣式可以根據自己要求改變