vue实现tab列表横向滚动时点击居中

vue实现tab列表横向滚动时点击居中_第1张图片
ezgif.com-optimize.gif

html结构

  • {{ i.name }}
内容

css样式

.topNav {
    height: 41rem / $model;
    background: #fff;
    display: flex;
    flex-flow:row nowrap; 
    overflow: scroll;   
    ul {
      display: inline-block;        
      white-space: nowrap;      
      li {
        display: inline-block;
        line-height: 41rem / $model;
        font-size: $fontS1;
        padding: 0 10px;
        &:first-child {
        }
        &:last-child {
        }
        &.current {
          position: relative;
          color: #66cc66;
          &:after {
            content: '';
            height: 4px;
            width: 30%;
            border-radius: 10px;
            background-color: #66cc66;
            position: absolute;
            bottom: 0.15rem;
            right: 35%;
          }
        }
      }
    }
  }

JS逻辑

goCenter(guid, index, e) {
      let destination = index - 2;
      destination = destination < 0 ? 1 : destination;
      this.currentTopNav = guid;
      if (this.navScroll) {
        this.navScroll.scrollToElement(
          document.querySelector('#topNav li:nth-child(' + destination + ')')
        );
      }
      this.getdata();

      // 横向滑动居中
      let ul = document.querySelector('#topNavUl');
      let nav = document.getElementById("topNav");
      let window_offsetWidth = window.innerWidth; //屏幕宽度;
      let dom = e.target;
      if (dom) {
        let domoffsetWidth = dom.offsetLeft,
          //中间值 =( 屏幕宽度 - li宽度 ) / 2;
          diffWidth = (window_offsetWidth - dom.offsetWidth) / 2,
          //目标值 = offset - 中间值
          targetOffset = -(domoffsetWidth - diffWidth);
        let ul_width = ul.getBoundingClientRect().width;//开始
        
        // 未超出中间值
        if (-targetOffset < 0) {
          nav.scrollLeft = 0;
          return;
        }
        //末尾
        if(targetOffset <  window_offsetWidth - ul_width ){
          nav.scrollLeft = -(window_offsetWidth - ul_width);
          return;
        }       
        //正常
        nav.scrollLeft = -targetOffset
      } 
    },

你可能感兴趣的:(vue实现tab列表横向滚动时点击居中)