实现哔哩哔哩点击小滑块移动效果

 中心知识:offsetLeft和offsetTop

获取元素距离自己定位父 级元素的左、上距离

核心思想就是将line设置一个单独的盒子,通过JS来判断点击对象,获取点击对象的offLeft值

然后再移动line的值,并且移动的值就是点击对象的offLeft

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>实现哔哩哔哩点击小滑块移动效果</title>
  <style>
    .box {
      position: relative;
      width: 800px;
      height: 80px;
      background-color: #333;
      margin: 0 auto;
    }

    .box a {
      display: block;
      text-decoration: none;
      float: left;
      color: #ccc;
      font-size: 30px;
      line-height: 80px;
      padding: 0 30px 0 30px;
    }

    .line {
      position: absolute;
      left: 20px;
      bottom: 0;
      width: 80px;
      border: 2px solid #ccc;
      transition: all 0.3s;
    }
  </style>
</head>

<body>
  <div class="box">
    <a href="#">首页</a>
    <a href="#">首页</a>
    <a href="#">首页</a>
    <a href="#">首页</a>
    <a href="#">首页</a>
    <a href="#">首页</a>
    <!-- 设置一个单独的盒子,用来移动下面的横线 -->
    <div class="line"></div>
  </div>
  <script>
    // 获取父元素,用事件委托
    const box = document.querySelector('.box')
    const line = document.querySelector('.line')
    box.addEventListener('click', function (e) {
      if (e.target.tagName === 'A') {
        // e.target.tagName 就是点击的当前元素
        // console.log(e.target.offsetLeft);
        line.style.transform = `translateX(${e.target.offsetLeft}px)`
      }
    })

  </script>

</body>

</html>

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值