这张图就是纯前端的方式写的
- 建立一个文本盒子
verifyCodeArray为循环的字母 ,charStyles里面装的是样式 :style="charStyles[index]" 样式不同
<a-col :span="5">
<div class="forgrtFrom_from_code" @click="generateVerifyCode">
<div
v-for="(char, index) in verifyCodeArray"
:key="index"
:style="charStyles[index]"
>
{{ char }}
</div>
<div
v-for="(line, index) in lines"
:key="index"
:style="lineStyles[index]"
></div>
</div>
</a-col>
- js 重点部分
// 随机验证码数组
const verifyCodeArray = ref<string[]>([]);
// 每个字符的样式数组
const charStyles = ref<Record<string, string>[]>([]);
// 线条数组
const lines = ref<number[]>(Array.from({ length: 16 }, (_, i) => i));
// 每条线条的样式数组
const lineStyles = ref<Record<string, string>[]>([]);
// 随机验证码
const generateVerifyCode = () => {
const chars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
let code = "";
for (let i = 0; i < 4; i++) {
code += chars.charAt(Math.floor(Math.random() * chars.length));
}
verifyCodeArray.value = code.split("");
const totalMargin = 4; // 左右各 10% 的边距
const availableWidth = 100 - totalMargin;
const charWidth = availableWidth / (verifyCodeArray.value.length + 3); // 每个字符宽度和间隔
const spacing = charWidth; // 字符间隔
// 生成每个字符的随机样式,从左到右排列
charStyles.value = verifyCodeArray.value.map((_, index) => {
const leftPercentage = totalMargin + (index + 1) * charWidth + index * 2;
const topPercentage = Math.random() * 30; // 随机上下偏移
return {
position: "absolute",
top: `${topPercentage}%`,
left: `${leftPercentage}%`,
fontSize: `${16 + Math.random() * 10}px`,
color: `rgb(${Math.random() * 255}, ${Math.random() * 255}, ${
Math.random() * 255
})`,
transform: `rotate(${Math.random() * 45 - 22.5}deg)`,
};
});
// 生成 10 条随机线条样式,设置为淡颜色
lineStyles.value = lines.value.map(() => ({
position: "absolute",
top: `${Math.random() * 100}%`,
left: `${Math.random() * 100}%`,
width: `${Math.random() * 80 + 20}%`,
height: "1px",
// 使用 rgba 设置淡颜色,最后一个参数 0.3 控制透明度
background: `rgba(${Math.random() * 255}, ${Math.random() * 255}, ${
Math.random() * 255
}, 0.3)`,
transform: `rotate(${Math.random() * 360}deg)`,
}));
};
// 初始化验证码
generateVerifyCode();
//点击发送验证码 开始60秒倒计时
const get_code = ref(false);
const get_code_time = ref(60);
//点击事件
const get_code_click = () => {
if (get_code.value) return; // 如果正在倒计时,不执行操作
get_code.value = true;
const timer = setInterval(() => {
get_code_time.value--;
if (get_code_time.value <= 0) {
clearInterval(timer);
get_code.value = false;
get_code_time.value = 60;
}
}, 1000);
};
在generateVerifyCode函数中 可以将样式 以及其他样式都可以在这里面一次生成
- css 部分
在样式盒子forgrtFrom_from_code 要使用 position: relative; 背景 ,盒子的宽高**以上就是我们前端生产的图文验证码啦 如有不明白的地方欢迎留言哈 感谢您的阅读 **