5

代码如下:

<!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>

效果如图所示:

图片描述


夕水
5.2k 声望5.7k 粉丝

问之以是非而观其志,穷之以辞辩而观其变,资之以计谋而观其识,告知以祸难而观其勇,醉之以酒而观其性,临之以利而观其廉,期之以事而观其信。