方块和按钮
<button id="btn1">块1向右移动</button>
<button id="btn2">块1向左移动</button>
<button id="btn3">块2向右移动</button>
<button id="btn4">块2向左移动</button>
<hr>
<div class="c1"></div>
<div class="c2"></div>
<div class="line"></div>
css修饰
```css
<style type="text/css">
div.c1 {
width: 150px;
height: 150px;
background-color: deeppink;
position:absolute;
}
div.c2 {
width: 150px;
height: 150px;
background-color: gold;
position: absolute;
top:200px;
}
div.line {
width: 0px;
height: 1000px;
position: absolute;
left: 800px;
border:1px solid red;
}
</style>
js添加功能
<script type="text/javascript">
/*
node 要移动的节点对象
attr 要改变的属性
target 移动到的目标值
step 步进值 符号由 目标值 - 当前值 决定
目标值 当前值
0 500 = 负
800 500 = 正
*/
// 获取块1
let c1 = document.querySelector('div.c1')
// 获取按钮1
let btn1 = document.querySelector('#btn1')
btn1.onclick = function(){
move(c1, 'left', 800, 10, ()=>{
move(c1, 'left', 0, 10, ()=>{
move(c1, 'width', 800, 10, ()=>{
move(c1, 'height', 400, 10)
})
})
});
}
// 获取按钮2
let btn2 = document.querySelector('#btn2')
btn2.onclick = function(){
move(c1, 'left', 0, 10);
}
// 获取按钮3
let c2 = document.querySelector('div.c2')
let btn3 = document.querySelector('#btn3')
btn3.onclick = function(){
move(c2, 'width', 800, 10);
}
document.querySelector('#btn4').onclick = function(){
move(c2, 'width', 0, 10);
}
function move(node, attr, target, step, callback){
clearInterval(node.hTime)
// 当前位置 大于 目标值, 所以每次就是 减step
if (getCur(node, attr) > target ) {
step = -step;
}
node.hTime = setInterval(()=>{
let newLeft = getCur(node,attr) + step
// 减,比最小还小 加,比最大还大 就停止
if (step<0 && newLeft<=target || step>0 && newLeft>=target) {
newLeft = target;
clearInterval(node.hTime)
// undefined
callback && callback();
}
node.style[attr] = newLeft + 'px'
},50)
}
/*
返回当前值
getCur(c1, 'width')
getComputedStyle(c1)['width']
150px
*/
function getCur(node, attr){
let val = getComputedStyle(node)[attr]
return parseFloat(val);
}
</script>
效果图
完成~