JS
function $(selector, all) {
if (all) {
return document.querySelectorAll(selector)
}
return document.querySelector(selector)
}
<style>
.box, .box2 {
width: 100px;
height: 100px;
position: absolute;
background-color:
top: 50px;
left: 100px;
}
.box2 {
top: 200px;
}
</style>
</head>
<body>
<div class="box">abc</div>
<div class="box2">box2</div>
<script src="js/tools.js"></script>
<script>
/**
* 运动函数
* @param element 待实现运动效果的元素
* @param attrName 操作的CSS属性名称
* @param end 运动目标终点值
* @param duration 运动总时长限制
*/
function animate(element, attrName, end, duration) {
// 先清除定时器
clearInterval(element.timer)
// 起始
const start = parseFloat(css(element, attrName))
// 运动起始时间
const startTime = Date.now()
// 开始运动,在当前 element 元素上绑定 timer 属性
// 用于记录定时器的 id(添加自定义属性)
element.timer = setInterval(() => {
// 获取到回调函数执行这一刻的时间
const currentTime = Date.now()
// 计算当前时间与运动起始时间差
const elapsed = Math.min(currentTime - startTime, duration)
// 按照公式,计算
const result = elapsed * (end - start) / duration + start
// 设置元素CSS属性值
element.style[attrName] = result + 'px'
// 判断是否到达终点,到达终点,停止定时器
if (elapsed === duration) {
clearInterval(element.timer)
}
}, 1000 / 60)
}
$('.box').onmouseover = function() {
animate(this, 'width', 300, 1000)
}
$('.box').onmouseout = function() {
animate(this, 'width', 100, 1000)
}
$('.box2').onmouseover = function() {
animate(this, 'width', 400, 1000)
}
$('.box2').onmouseout = function() {
animate(this, 'width', 100, 1000)
}
</script>
</body>