在用JS编写动画的时候,经常用会到布局转换,即在运动前将相对定位转为绝对定位,然后执行动画函数。下面给大家分享一个运用原生JS实现的布局转换的Demo,效果如下:
以下是代码实现,欢迎大家复制粘贴及吐槽。
代码语言:javascript复制<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>原生JS实现动画中的布局转换</title>
<style>
* {
margin: 0;
padding: 0;
}
#ul1 {
width: 366px;
margin: 0 auto;
position: relative;
}
#ul1 li {
list-style: none;
width: 100px;
height: 100px;
background: #CCC;
border: 1px solid black;
float: left;
margin: 10px;
z-index: 1;
}
</style>
<!-- 运动框架 -->
<script>
// 获取指定样式的值
function getStyle(obj, attr) {
if (obj.currentStyle) {
return obj.currentStyle[attr];
} else {
return getComputedStyle(obj, false)[attr];
}
};
// 运动函数
function startMove(obj, json, fn) {
clearInterval(obj.timer);
obj.timer = setInterval(function () {
var bStop = true;
for (var attr in json) {
var iCur = 0;
if (attr == 'opacity') {
iCur = parseInt(parseFloat(getStyle(obj, attr)) * 100);
} else {
iCur = parseInt(getStyle(obj, attr));
}
var iSpeed = (json[attr] - iCur) / 8;
iSpeed = iSpeed > 0 ? Math.ceil(iSpeed) : Math.floor(iSpeed);
if (iCur != json[attr]) {
bStop = false;
}
if (attr == 'opacity') {
obj.style.filter = 'alpha(opacity:' (iCur iSpeed) ')';
obj.style.opacity = (iCur iSpeed) / 100;
} else {
obj.style[attr] = iCur iSpeed 'px';
}
}
if (bStop) {
clearInterval(obj.timer);
if (fn) {
fn();
}
}
}, 30)
}
</script>
<!-- 添加事件 -->
<script>
window.onload = function () {
var oUl = document.getElementById('ul1');
var aLi = oUl.getElementsByTagName('li');
var iMinZindex = 2;
var i = 0;
// 1.布局转换
for (i = 0; i < aLi.length; i ) {
//aLi[i].innerHTML='left:' aLi[i].offsetLeft ', top:' aLi[i].offsetTop;
aLi[i].style.left = aLi[i].offsetLeft 'px';
aLi[i].style.top = aLi[i].offsetTop 'px';
}
// 必需要用两个循环
for (i = 0; i < aLi.length; i ) {
aLi[i].style.position = 'absolute';
//第一次循环中offset值已经计算了原有的margin值,所以此处要清除
aLi[i].style.margin = '0';
}
// 2.加事件
for (i = 0; i < aLi.length; i ) {
aLi[i].onmouseover = function () {
//让当前zIndex不断的增加,防止堆叠
this.style.zIndex = iMinZindex ;
startMove(this, {
width: 200,
height: 200,
marginLeft: -50,
marginTop: -50
});
};
aLi[i].onmouseout = function () {
startMove(this, {
width: 100,
height: 100,
marginLeft: 0,
marginTop: 0
});
};
}
};
</script>
</head>
<body>
<ul id="ul1">
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</body>
</html>