我报名参加金石计划1期挑战——瓜分10万奖池,这是我的第1篇文章,点击查看活动详情
今天天气比较冷,在上班的路上突然看到好多人带了帽子,然后我突然奇想我能不能用我所掌握的技术来实现一个帽子并给他添加上一些小功能,接下来我们来实现一下吧!
效果图
页面结构
页面结构我们只有一个大盒子,大盒子里面有一个魔术帽承载盒子以及魔术帽变色按钮,当魔术帽变色按钮点击后魔术帽的颜色会发生改变
<div id="app">
<!-- 魔术帽 -->
<div>
<div class="hat"></div>
<div class="brim"></div>
</div>
<div>
<!-- 魔术帽按钮 -->
<button id="btn">魔术帽变色</button>
</div>
</div>
初始样式
清除所有元素的内边距外边距
* {
margin: 0;
padding: 0;
}
使用定位的方式让大盒子页面居中,然后使用flex布局,先将Y轴设置为主轴,然后再让里面的内容Y轴居中和X轴居中
#app {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
让大盒子里面的元素也使用flex布局X轴居中和Y轴居中
#app>div {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
margin-bottom: 20px;
}
帽子样式
设置好帽子的宽高,用边框圆角属性让帽子变成一个半圆,然后给上背景色,再让设置下边框属性,用此充当帽子连接处
.hat {
height: 150px;
width: 300px;
border-radius: 150px 150px 0 0;
background: #08ef5d;
border-bottom: 20px solid #0bec2d;
}
帽檐样式
我们设置好帽檐的宽高,然后通过边框圆角属性给出效果,设置好背景色,我们由于使用flex布局Y轴为主轴,X轴居中,所以我们这里不需要给其他设置,就可实现一个帽子的效果
.brim {
height: 50px;
width: 400px;
border-radius: 400px 400px 0 0;
background: #37ff00;
}
帽子变色逻辑
// 获取魔术帽变色按钮
const btn = document.getElementById('btn');
// 获取帽子元素
const hat = document.getElementsByClassName('hat')[0];
// 获取帽檐元素
const brim = document.getElementsByClassName('brim')[0];
// 当魔术帽变色按钮点击时
btn.onclick = () => {
// 随机获取3个0~255之间的数用于更换背景色
const R = Math.round(Math.random() * 255);
const G = Math.round(Math.random() * 255);
const B = Math.round(Math.random() * 255);
// 给魔术帽重新赋值颜色
hat.style.backgroundColor = `rgb(${R},${G},${B})`;
// 给魔术帽连接处重新赋值颜色
hat.style.borderBottomColor = `rgb(${G},${B},${R})`;
// 给魔术帽帽檐重新赋值颜色
brim.style.backgroundColor = `rgb(${B},${G},${R})`;
}
代码放到码上掘金了,感兴趣的大家可以看一看!
坚持努力,无惧未来!