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%;
}

然后运行项目,就可以达到想要的效果了,样式可以根据自己要求改变

posted @ 2020-08-23 11:23  孤水寒月  阅读(1118)  评论(0编辑  收藏  举报