目录
一、HTML布局
二、CSS布局
三、JavaScript代码——移动
四、JavaScript代码——缓动
五、完整代码
一、HTML布局
简单定义两个盒子,一个做移动效果、一个做缓动效果。
<div class="box box1"></div><div class="box box2"></div>
二、CSS布局
为两个盒子定义宽高和背景色,随便做个效果哦!能看就管,
<style>*{padding:0px;margin:0px;}.box{width: 200px;height: 200px;background: blue;position: absolute;left:0px;}.box2{background: red;margin-top: 210px;}</style>
三、JavaScript代码——移动
1.获取元素
把刚才html定义的元素获取过来在js中运用。
var box1 = document.querySelector('.box1');
var box2 = document.querySelector('.box2');
2.封装函数实现移动
num:定义盒子每次都移动h1个像素。
target: 每次移动的距离。
if判断:通过if来判断,到达了设定距离,就会删除间隔函数。
box.style.left:没有达到距离,一直赋值给‘盒子’左边距。
myRun:给盒子设计点击事件,点击才会出现移动,this指向box1,里面是所调用的值,可以直接在里面修改,移动一次的距离,一共移动的距离。
function myRun(box,h1,h2){
var myInter = setInterval(function(){
var offsetLeft = box.offsetLeft;
var num = h1;
var target = h2;
if(offsetLeft==target){ clearInterval(myInter);}else{box.style.left = offsetLeft+num+'px';}},1000)}box1.onclick=function(){myRun(this,50,200); }
移动效果
四、JavaScript代码——缓动
与移动同理使用函数来封装,代码大致与js移动相同,中间判断与上文稍微有些不同,其中的含义是,第一次移动取移动距离的十分之一,接下来的每一次移动,都是取省下来还剩多少距离的十分之一,取整是为了,在无线接近于所设置的距离可以移动。
function move(obj,sum){var liLi = setInterval(function(){var offsetLeft =obj.offsetLeft;var num = (sum - offsetLeft)/10;num > 0 ? Math.ceil(num):Math.floor(num);if(offsetLeft==sum){clearInterval(liLi);}else{obj.style.left = offsetLeft+num+'px';}},1000)} box2.onclick=function(){move(this,200);}
缓动效果
五、完整代码
1.移动代码
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><title>移动</title><style>* {padding: 0px;margin: 0px;}.box {width: 200px;height: 200px;background: blue;position: absolute;left: 0px}.box2 {background: red;margin-top: 210px;}</style>
</head><body><div class="box box1"></div><div class="box box2"></div><script>var box1 = document.querySelector('.box1');var box2 = document.querySelector('.box2');function myRun(box, h1, h2) {var myInter = setInterval(function () {var offsetLeft = box.offsetLeft;var num = h1;var target = h2;if (offsetLeft == target) {clearInterval(myInter);} else {box.style.left = offsetLeft + num + 'px';}}, 1000)}box1.onclick = function () {myRun(this, 50, 200);} </script>
</body></html>
2.缓动效果
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><title>移动</title><style>* {padding: 0px;margin: 0px;}.box {width: 200px;height: 200px;background: blue;position: absolute;left: 0px}.box2 {background: red;margin-top: 210px;}</style>
</head><body><div class="box box1"></div><div class="box box2"></div><script>var box1 = document.querySelector('.box1');var box2 = document.querySelector('.box2');function move(obj, sum) {var liLi = setInterval(function () {var offsetLeft = obj.offsetLeft;var num = (sum - offsetLeft) / 10;num > 0 ? Math.ceil(num) : Math.floor(num);if (offsetLeft == sum) {clearInterval(liLi);} else {obj.style.left = offsetLeft + num + 'px';}}, 1000)} box2.onclick = function () {move(this, 200);}</script>
</body></html>