关于Ui-提示的封装
在平时写项目的时候总会遇到各种弹窗,这些弹窗当然不算难写,但其代码数量之多,以及重复率很高,所以我就想着使用一个函数和css对我们常见的提示性弹窗进行了封装,可以重复调用,并且也可以有效的提高服务器解析html的效率
JS代码
在JS代码中需要注意的是,当调用时需要为其设置默认属性,以保证在使用时出现了类型错误导致无法调用,并且提醒用户需要更改信息以保证代码的正常运行
function tipUi(tip) {
tip.color = !tip.color ? 'black' : tip.color;
let p = document.createElement('p');
// 判断文本类型(提示,错误,正确)
let textContent = '';
switch (tip.type) {
case '提示':
textContent = '';
break;
case '成功':
textContent = '';
break;
case '失败':
textContent = '';
break;
default:
// 抛出警告,表示用户输入的类型只能是'提示','成功','失败'
console.warn("The type of text you fill in does not meet the requirements, and the types are'提示','成功','失败'");
textContent = '';
break;
}
p.innerHTML = `<i class="iconfont">${textContent}</i> ${tip.msg}`;
function isValidColor(color) {
const div = document.createElement("div");
div.style.color = color;
return div.style.color !== "";
}
if (isValidColor(tip.color)) {
p.style.color = tip.color;
} else {
p.style.color = 'black';
// 用户输入的颜色不合法
console.warn("The color you set does not exist");
}
p.setAttribute('class', 'tipUi');
document.body.appendChild(p);
let time = setTimeout(() => {
p.classList.add('top');
clearTimeout(time);
}, 500)
let clear = setTimeout(() => {
p.remove();
clearTimeout(clear);
}, 1000)
}
css
.tipUi {
z-index: 15000;
opacity: 1;
padding: 7px 20px;
display: flex;
align-items: center;
position: fixed;
top: 10%;
min-width: 200px;
font-size: 15px;
font-weight: 200;
transition-duration: 1s;
left: 50%;
transform: translate(-50%, -50%);
background-color: #FFF;
border-radius: 3px;
box-shadow: 1px 2.5px 10px 2px gainsboro;
}
.tipUi i {
font-size: 20px;
}
示例
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="../UI/tip.css">
</head>
<body>
<script src="../UI/tip.js">
</script>
<script>
let tip = {
type: '失败',
msg: '失败了,小卡拉米😒😒😒',
color: 'red'
}
tipUi(tip);
</script>
</body>
效果图
输入错误信息
let tip = {
type: '将军',
msg: '失败了,小卡拉米😒😒😒',
color: '676767'
}
tipUi(tip);
值得注意的是我们在设置ui的class类名和函数名时需要稍微复杂繁琐一点,这样可以有效的避免在函数声明的时候实现命名重复的错误
生活周记
这周感觉过的挺快的,又要开始上排球课了,好烦,希望今天下雨就不用去了~~
这周我们小组进行了小组招新的排练。emem~~,还是有点生疏在身上的,少点活力,有点过于严肃了,好像我在当老师在和他们讲课😵💫
接下来一周的计划是
1.整理算法错题,复习java基础知识
2.整理一下自己的项目,复习JS和ES6知识
3.继续完善音乐学院的项目(马上就要结束啦)