原生js实现手机端导航滑动效果

代码如下:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>导航效果</title>
    <style>
      div,
      li,
      ul,
      a {
        margin: 0;
        padding: 0;
      }
      ul,
      li {
        list-style: none;
      }
      ul {
        width: 500px;
        height: 35px;
        display: block;
        white-space: nowrap;
        overflow: hidden;
        overflow-x: auto;
        border-bottom: 1px solid #dd3;
      }
      ul > li {
        width: 60px;
        height: 35px;
        display: inline-block;
        cursor: pointer;
        color: #8d19f3;
        font-size: 18px;
        text-align: center;
        line-height: 35px;
      }
      ul > li:not(:first-child) {
        margin-left: 25px;
      }
      ::-webkit-scrollbar {
        width: 0;
        height: 0;
      }
    </style>
  </head>
  <body>
    <ul class="box">
      <li>导航一</li>
      <li>导航二</li>
      <li>导航三</li>
      <li>导航四</li>
      <li>导航五</li>
      <li>导航六</li>
      <li>导航七</li>
      <li>导航八</li>
      <li>导航九</li>
      <li>导航十</li>
      <li>导航十一</li>
      <li>导航十二</li>
      <li>导航十三</li>
      <li>导航十四</li>
      <li>导航十五</li>
      <li>导航十六</li>
    </ul>
    <script>
      var timer = null,
        parentElement = document.querySelector(".box"),
        childElement = document.querySelectorAll("li");
      for (var i = 0, len = childElement.length; i < len; i++) {
        childElement[i].index = i;
        childElement[i].onclick = function() {
          var offsetLeft = childElement[this.index].offsetLeft,
            scrollX = parentElement.scrollLeft,
            clientX = parentElement.clientWidth,
            childClientX = childElement[this.index].clientWidth;
          var speed = offsetLeft - scrollX + childClientX / 2 - clientX / 2,
            s = speed / 40,
            totalX = speed + scrollX;
          timer = setInterval(function() {
            parentElement.scrollLeft += s;
            if (
              parentElement.scrollLeft <= 0 ||
              parentElement.scrollLeft >= parentElement.scrollWidth - clientX ||
              (speed > 0 && parentElement.scrollLeft > totalX) ||
              (speed < 0 && parentElement.scrollLeft < totalX)
            ) {
              clearInterval(timer);
            }
          }, 10);
        };
      }
    </script>
  </body>
</html>

效果如图所示:

图片描述

阅读 1.1k

推荐阅读
eveningwater
用户专栏

每天学习一点点,就可以进步一点点,工作能带来的不仅是技术知识点,还有与人的相处,沟通与交流。这是...

8 人关注
23 篇文章
专栏主页