单属性运动函数封装

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: #f00;
      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>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值