第一次收到笔试题,发现自己存在很多不足。再次进行复习。
事件流
事件流指的是事件被触发传播的三个阶段。根据顺序可以分成:
事件捕获阶段、处于目标阶段、事件冒泡阶段
在事件流的基础上出现了事件委托。事件委托指的是把子级元素的事件委托给父级元素 处理。这样做的好处是可以减少事件绑定。原理是DOM元素的事件冒泡。
CSS居中
首先绘制一个组件
<body>
<div class="box">
<div class="item">
我在尝试css中的水平垂直居中
</div>
</div>
</body>
<style>
*{
margin: 0;
padding: 0;
}
.box{
width: 500px;
height: 500px;
border: 4px solid olivedrab;
border-radius: 5px;
}
.item{
width: 300px;
height: 70px;
background-color: #ccc;
}
</style>
效果如图:
我们想让中间灰色的item水平垂直居中。
第一种方法:
思路是我们让item相对于box进行移动,移动到中心点。根据子绝父相原则,先让item左边距离box50%,上边也50%
.box{
position: relative;
width: 500px;
height: 500px;
border: 4px solid olivedrab;
border-radius: 5px;
}
.item{
position: absolute;
width: 300px;
height: 70px;
background-color: #ccc;
left: 50%;
top: 50%;
}
效果如上,我们发现是item左上角居中了,整体的块并没有居中。需要把它往左边和上面拉。拉的距离就是box尺寸的一半。
.item{
position: relative;
width: 300px;
height: 70px;
background-color: #ccc;
left: 50%;
top: 50%;
margin-left: -150px;
margin-top: -35px;
}
效果已经实现了!!成功!!
但是这个方法的缺点是我们要计算item的宽高,很不智能!
那怎么在不用计算尺寸的情况下实现水平垂直居中呢?
首先我们还是保留子绝父相,然后把item的left——bottom全部设为0.
.item{
position: absolute;
width: 300px;
height: 70px;
background-color: #ccc;
left: 0;
top: 0;
right: 0;
bottom: 0;
}
这个时候顶格显示。再加上一句话:margin:auto
马上居中了!这种情况也有一个缺点,那就是item必须定义宽高。如果没有定义宽高就会出现:
全部占满。
那怎么在没有固定尺寸的情况下实现水平垂直居中?
这种方法跟方法一类似,也是用left、top定位,是目前实战中最频繁使用的。不同在于不需要计算宽高,也不需要item有固定尺寸。只需要一句
transform: translate(-50%,-50%);
.item{
position: absolute;
background-color: #ccc;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
/* width: 300px;
height: 70px; */
}
第四种方法就运用到了flex布局。第四种方法只需要针对box元素来写样式。
不需要子绝父相,三行代码搞定
.box{
/* position: relative; */
display: flex;
justify-content: center;
align-items: center;
width: 500px;
height: 500px;
border: 4px solid olivedrab;
border-radius: 5px;
}
.item{
/* position: absolute; */
background-color: #ccc;
/* left: 50%;
top: 50%;
transform: translate(-50%,-50%); */
/* width: 300px;
height: 70px; */
}