JS运动总结封装
1.匀速运动,往返运动
function constantBack(node, speed, target, node1, node2) {
let time = null;
let time1 = null
node1.addEventListener("click", function() {
clearInterval(time)
clearInterval(time1)
time = setInterval(() => {
node.style.left = node.offsetLeft + speed + "px"
if (node.offsetLeft > target) {
node.style.left = target + "px"
clearInterval(time)
}
}, 50);
})
node2.addEventListener("click", function() {
clearInterval(time)
clearInterval(time1)
time1 = setInterval(() => {
node.style.left = node.offsetLeft - speed + "px"
if (node.offsetLeft < 0) {
node.style.left = 0 + "px"
clearInterval(time1)
}
}, 50);
})
}
2. 匀速透明运动
function linerOpac(node, speed) {
let time = null
let time1 = null
node.onmouseover = function() {
clearInterval(time1)
clearInterval(time)
time = setInterval(() => {
node.style.opacity = Number(getComputedStyle(node, false)["opacity"]) - speed
if (node.style.opacity < 0) {
node.style.opacity = 0
clearInterval(time)
}
}, 50);
}
node.onmouseout = function() {
clearInterval(time)
clearInterval(time1)
time1 = setInterval(() => {
node.style.opacity = Number(getComputedStyle(node, false)["opacity"]) + speed
if (node.style.opacity > 1) {
node.style.opacity = 1
clearInterval(time1)
}
}, 50);
}
}
3. 缓冲运动
function bufferRun(node, target, node1, node2) {
let time = null;
let time1 = null
node1.addEventListener("click", function() {
clearInterval(time)
clearInterval(time1)
time = setInterval(() => {
node.style.left = node.offsetLeft + Math.ceil((target - node.offsetLeft) / 10) + "px"
if (node.offsetLeft > target) {
node.style.left = target + "px"
clearInterval(time)
}
}, 50);
})
node2.addEventListener("click", function() {
clearInterval(time)
clearInterval(time1)
time1 = setInterval(() => {
node.style.left = node.offsetLeft - Math.ceil((node.offsetLeft) / 10) + "px"
if (node.offsetLeft < 0) {
node.style.left = 0 + "px"
clearInterval(time1)
}
}, 50);
})
}
4. 反弹运动
function rebound(node, leftMax, topMax) {
let speedL = Math.round(Math.random() * 5 + 5)
let speedT = Math.round(Math.random() * 5 + 5)
time = setInterval(() => {
console.log(leftMax, topMax);
node.style.left = node.offsetLeft + speedL + "px"
node.style.top = node.offsetTop + speedT + "px"
if (node.offsetLeft >= leftMax || node.offsetLeft < 0) {
speedL = -speedL
}
if (node.offsetTop >= topMax || node.offsetTop < 0) {
speedT = -speedT
console.log(speedT);
}
}, 50);
}