1、先写出html和css样式,
<style>
* {
margin: 0;
padding: 0;
}
.box {
position: absolute;
width: 100px;
height: 100px;
background-color: pink;
}
.ha {
position: absolute;
top: 300px;
left: 400px;
width: 200px;
height: 200px;
background-color: purple;
color: aliceblue;
}
body {
height: 1000px;
font-size: 20px;
}
</style>
</head>
<body>
<div class="box">gump盒子移动到100</div>
<div class="gump">gump盒子移动到500</div>
效果如图所示:重要是学js技术,样式好看不好看无所谓啊~
2、接下来写js,我直接在下面写的,所以没用load
3、封装一个动画函数,添加点击事件,事件中调用动画函数,点击两个盒子实现渐变动画
4、解释超详细,有需要讨论的点评论即可~
<script>
var box = document.querySelector('.box');
var gump = document.querySelector('.gump');
// 函数封装一个渐变动画
function animate(obj, target) {
// 让函数中始终只有一个定时器
clearInterval(obj.timer);
obj.timer = window.setInterval(function() {
// 如果到达目标位置就停止(清除定时器)
if (obj.offsetLeft == target) {
clearInterval(obj.timer)
}
// 每调用一次定时器就重新计算一次step的长度,目标长度不变,现在的位置离目标距离越来越近
// 他们之间的差的绝对值也就越来越小,使得间隔时间内每一步的长度减小,实现渐慢效果
// 第一步:(500-100)/10 = 40 第二步:(500-140)/10 = 36 ......
var step = (target - obj.offsetLeft) / 10;
// 如果步长为正,取较大的整数;如果步长为负,取较小的额整数。目的都是取绝对值较大的
step > 0 ? step = Math.ceil((step)) : step = Math.floor(step);
// obj.style.left可读写,但只能获取行内的样式,所以用来”写” 数据极好
// obj.offsetLeft 只能读,但他能读行内样式,内嵌样式,外链样式,”读”数据极好
obj.style.left = obj.offsetLeft + step + 'px';
}, 20);
}var box1 = box.addEventListener('click', function() {
animate(gump, 100);})
var box2 = gump.addEventListener('click', function() {
animate(gump, 500);})
</script>