实现下图的遮罩层loading旋转。
但是旋转的时候却发现旋转块发生了位置偏移。
代码如下
<div class="mask">
<div class="load-circle">
</div>
</div>
/* 遮罩层 */
.mask {
width: 100%;
height: 100%;
position: fixed;
top: 0;
left: 0;
background: #3958fe;
z-index: 999;
}
/* 旋转圆圈 */
.mask .load-circle {
width: 29px;
height: 29px;
border-radius: 50%;
border: 5px solid #fff;
border-right: 5px solid #3958fe;
position: absolute;
top: 50%;
left: 50%;
transform:translate(-50%,-50%); /******* 导致发生偏移的问题代码 *******/
-webkit-transition-property: -webkit-transform;
-webkit-transition-duration: .9s;
-moz-transition-property: -moz-transform;
-moz-transition-duration: .9s;
-webkit-animation: rotate .9s linear infinite;
-moz-animation: rotate .9s linear infinite;
-o-animation: rotate .9s linear infinite;
animation: rotate .9s linear infinite;
}
/* 旋转动画 */
@-webkit-keyframes rotate {
from{ -webkit-transform: rotate(0deg) }
to{ -webkit-transform: rotate(360deg) }
}
@-moz-keyframes rotate {
from{ -moz-transform: rotate(0deg) }
to{ -moz-transform: rotate(360deg) }
}
@-o-keyframes rotate {
from{ -o-transform: rotate(0deg) }
to{ -o-transform: rotate(360deg) }
}
@keyframes rotate {
from{ transform: rotate(0deg) }
to{ transform: rotate(360deg) }
}
把问题代码揪出来
position: absolute;
top: 50%;
left: 50%;
transform:translate(-50%,-50%);
是我常用的居中css样式。怎知在这里就成了bug。
看看css手册。旋转用到了 transform,我居中定位也用到了transform,两个搅在一起不打架才奇怪。
这个时候只能放弃 transform的居中写法。采用其他居中写法。
因为旋转的div宽高固定,可以改写为这样子居中
position: absolute;
top: 50%;
left: 50%;
margin-left: -17px;
margin-top: -17px;
旋转的动画如下(有时候为了浏览器兼容,会加上浏览器内核前缀重复定义动画)
@keyframes rotate {
from { transform: rotate(0deg) }
to { transform: rotate(360deg)}
}
为一个div添加无限旋转(有时候为了浏览器兼容,会加上浏览器内核前缀重复定义动画)
div {
animation: rotate 1s linear infinite;
-webkit-animation: rotate 1s linear infinite; /* Safari 和 Chrome */
}
animation语法