html+css+js简单的实现一个小黄人
说好html+css+js,那么三个页面肯定要有
实现方法第一时间想到的有两种:
方法一:1个按钮,1个总盒子包括多个小盒子,在按钮发生点击事件的时候去修改样式,触发,使起成为整体;
方法二:利用节点和循环,这样就可以省去html页面的复杂操作
接下来就是开始实现了:
html页面
<!-- css和js都叫3d box -->
<link rel="stylesheet" href="./3d box.css">
<body>
<!--
1.需要一个按钮和一个大盒子
-->
<button id="btn" class="c_btn">试试看 🎩</button>
<div id="z_box" class="boxes big"></div>
<script src="./3d box.js"></script>
</body>
css页面:涉及盒子一系列操作,比如:绝对、相对、固定定位;flex布局;视窗单位等等;
可以算是把绝大部分都用得上的css都包含在其中了,话不多说:代码放在下方
*{
box-sizing: border-box;
}
body{
/* 设置页面高度为浏览器视窗高度 */
height: 100vh;
/* 设置背景颜色 */
background-color: #fff;
/*设置字体类型*/
font-family: 'Roboto',sans-serif;
/*flex 布局*/
display: flex;
/*修改主轴为垂直方向*/
flex-direction: column;
/*沿侧轴居中排列*/
align-items: center;
/*主轴对齐方式*/
justify-content: center;
/*溢出隐藏*/
overflow: hidden;
}
.c_btn{
/* 固定定位 */
position: fixed;
top: 20px;
/* 层级 */
z-index: 100;
/*去边框*/
border: 0;
/* 内边距 */
padding: 0 20px;
/*圆角*/
border-radius: 3px;
/*增加字符间的空白*/
letter-spacing: 2px;
/* 高度 */
height: 50px;
/*背景颜色*/
background-color: #f9ca24;
/* 盒子阴影 */
box-shadow: 0 3px rgba(249, 202, 36, 0.5);
/*行高*/
line-height: 40px;
/*字体大小*/
font-size: 16px;
/*字体颜色*/
color: #fff;
}
.boxes{
/* 相对定位 */
position: relative;
/*开启弹性盒子*/
display: flex;
/* 弹性盒子自动换行 */
flex-wrap: wrap;
/*弹性盒子沿主轴均匀排列*/
justify-content: space-around;
/* 过渡 */
transition: 0.4s ease;
height: 500px;
width: 500px;
}
.boxes.big {
width: 600px;
height: 600px;
}
.boxes.big .box {
/* 沿z轴旋转360度 */
transform: rotateZ(360deg);
}
.box {
/* 相对定位 */
position: relative;
/* 背景图片路径 */
background-image: url('https://media.giphy.com/media/EZqwsBSPlvSda/giphy.gif');
/* 背景平铺: no-repeat 不平铺*/
background-repeat: no-repeat;
/* 设置背景图片大小 */
background-size: 500px 500px;
height: 125px;
width: 125px;
/* 过渡 */
transition: 0.4s ease;
}
/* 在元素的最后添加 */
.box::after {
content: '';
background-color: #f6e58d;
/* 绝对定位 */
position: absolute;
top: 8px;
right: -15px;
height: 100%;
width: 15px;
/* 2d动画偏斜45度 */
transform: skewY(45deg);
}
/* 在元素的开头添加 */
.box::before {
content: '';
/* 背景颜色 */
background-color: #f9ca24;
/* 绝对定位 */
position: absolute;
bottom: -15px;
left: 8px;
height: 15px;
width: 100%;
/* 2d动画偏斜45度 */
transform: skewX(45deg);
}
有学习过小伙伴都经历过打印5行5列的*了吧,其实小盒子的也一样,利用节点创建,赋予类,添加,事件都是对其进行细微调整的
// 获取总盒子
const z_box = document.getElementById('z_box')
//获取按钮
const btn = document.querySelector('button')
//点击事件,添加类,有就添加没有就删除
btn.addEventListener('click', () => z_box.classList.toggle('big'))
for (let j = 0; j < 4; j++) {
// 创建名为box的盒子节点
const div = document.createElement('div')
//给创建的box盒子统一添加box类
div.classList.add('box')
//添加box盒子 背景位置
div.style.backgroundPosition = `${-j * 125}px ${-i * 125}px`
//添加box盒子节点到总盒子
z_box.appendChild(div)
}
这样一个能复习到html+css+js基础的小项目就完成了;
这个小项目来源github上的开源项目:github.com/bradtravers…;
感兴趣的小伙伴可以去看看;