<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box {
width: 100px;
height: 100px;
background: #000;
position: absolute;
transition: all 0.5s;
}
</style>
</head>
<body>
<div class="box"></div>
<!-- <script>
// 回调方法
function move(el, direction, target, cb) {
let star = parseInt(el.style[direction]) || 0
console.log(star)
let speed = 10
star += (target - star) > 0 ? speed : -speed
setTimeout(() => {
if (star == target) {
cb && cb()
} else {
el.style[direction] = star + "px";
move(el, direction, target, cb)
}
}, 100)
}
let box = document.querySelector(".box")
// 回到地狱,层层嵌套
move(box, "left", 300, function () {
console.log("运动完成1")
move(box, "top", 300, function () {
console.log("运动完成2")
move(box, "left", 0, function () {
console.log("运动完成3")
move(box, "top", 0, function () {
console.log("运动完成4")
})
})
})
})
</script> -->
<script>
//自定义事件,没有回调函数的层层嵌套,利于维护
// 自定义事件触发器
let myevent = new EventTarget()
myevent.num = 1
function move(el, direction, target, cb) {
let star = parseInt(el.style[direction]) || 0
// console.log(star)
let speed = 10
star += (target - star) > 0 ? speed : -speed
setTimeout(() => {
if (star == target) {
// 触发自定义事件,创建自定义事件对象(实例化)
myevent.dispatchEvent(new CustomEvent("myevents" + myevent.num))
myevent.num++
} else {
el.style[direction] = star + "px";
move(el, direction, target, cb)
}
}, 100)
}
let box = document.querySelector(".box")
move(box, "left", 300)
//添加事件监听触发执行函数
myevent.addEventListener("myevents1", function () {
console.log("第一完成运动")
move(box, "top", 300)
})
myevent.addEventListener("myevents2", function () {
console.log("第二完成运动")
move(box, "left", 0)
})
myevent.addEventListener("myevents3", function () {
console.log("第三完成运动")
move(box, "top", 0)
})
myevent.addEventListener("myevents4", function () {
console.log("完成运动")
})
</script>
<script>
// // promise链式调用
// function move(el, direction, target) {
// return new Promise(resolve => {
// // 使用闭包函数调用外部变量,递归
// function fn() {
// let star = parseInt(el.style[direction]) || 0
// let speed = 10
// star += (target - star) > 0 ? speed : -speed
// setTimeout(() => {
// if (star == target) {
// resolve()
// } else {
// el.style[direction] = star + "px";
// fn()
// }
// }, 100)
// }
// fn()
// })
// }
// let box = document.querySelector(".box")
// // 链式执行return Promise对象
// move(box, "left", 300).then(res => {
// console.log("运动成功1")
// return move(box, "top", 300)
// }).then(res => {
// console.log("运动成功2")
// return move(box, "left", 0)
// }).then(res => {
// console.log("运动成功3")
// return move(box, "top", 0)
// }).then(res => {
// console.log("运动成功4")
// })</script>
</body>
</html>
js控制元素移动,回调写法和自定义事件监听调用
最新推荐文章于 2023-08-16 10:30:00 发布