js和jquery选项卡菜单自动居中

js和jquery选项卡菜单自动居中

效果如下

在这里插入图片描述

代码如下

代码分为js和jquery部分

<!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>js选项卡居中</title>
  <script src="./js/jq.js"></script>
  <style>
    .container {
      height: 200px;
      width: 800px;
      background-color: #eee;
      white-space: nowrap;
      overflow: auto;
      position: relative;
      /* 可以使窗口平稳滚动 */
      scroll-behavior: smooth;
      margin: 0 auto;
    }

    .item {
      width: 220px;
      height: 100px;
      background-color: blue;
      display: inline-block;
      text-align: center;
      line-height: 100px;
    }

    .item:nth-child(2n) {
      background-color: pink;
    }
  </style>

</head>

<body>
  <div class="container">
    <div class="item">1</div>
    <div class="item">2</div>
    <div class="item">3</div>
    <div class="item">4</div>
    <div class="item">5</div>
    <div class="item">6</div>
    <div class="item">7</div>
    <div class="item">8</div>
    <div class="item">9</div>
    <div class="item">10</div>
  </div>

</body>

</html>
<script>
  /**
   * Jquery代码
  */
  $(function () {
    let tabUlWidth = parseInt($(".container").css("width"))
    $(".container .item").click(function () {
      const itemLeft = $(this)[0].offsetLeft
      const itemMarginRight = parseInt($(this).css("marginRight"))
      const itenWidth = parseInt($(this).css("width"))

      const scrollLeftNum = itemLeft - tabUlWidth / 2 + itenWidth / 2
      $(this).parent().scrollLeft(scrollLeftNum)
      console.log('itemLeft', itemLeft);
    })


  })

  /**
    * JS代码
   */

  // // 获取到 container 整个盒子
  // var container = document.querySelector(".container");

  // // 获取包裹盒子 container.offsetWidth
  // var containerW = container.offsetWidth;

  // // 找到所有需要被点击的 item 的集合
  // var itemList = document.querySelectorAll(".item");

  // // 遍历数组
  // for (let i = 0; i < itemList.length; i++) {
  //   // 给每个元素添加点击事件
  //   itemList[i].onclick = function () {

  //     // 获取到当前点击元素的 offsetLeft  - 包裹盒子 offsetWidth 的一半 + 当前点击元素 offsetWidth 的一半
  //     var scrollLeftNum = itemList[i].offsetLeft - containerW / 2 + itemList[i].offsetWidth / 2;
  //     // console.log(scrollLeftNum, '距离',itemList[i].offsetLeft)

  //     // 赋值
  //     container.scrollLeft = scrollLeftNum;
  //   }
  // }
</script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值