css 文字随 switch 开关渐变颜色(KTV字幕效果)

551 阅读1分钟

html

      <div class="message_type">
        <div
          class="option_per"
          :class="{ option_active: index === messages.index }"
          v-for="(item, index) of messages.options"
          :key="index"
          @click.stop="messages.index = index"
        >
          {{ item.text }}
        </div>
      </div>

Vue.js


  data() {
    return {
      /**
       * 信息类型
       */
      messages: {
        // 选项
        options: [
          {
            text: "@我",
          },
          {
            text: "全部",
          },
        ],

        index: 0, // 选中索引
      },
    };

  computed: {
    /**
     * 中心选项 css 变量 选中 index 值
     */
    centerCssVariable() {
      const { index } = this.messages;
      const result = {
        "--index": index,
      };
      return result;
    },
  },

CSS


    .message_type {
      display: flex;
      align-items: center;
      justify-content: space-between;
      width: 194rpx;
      height: 56rpx;
      border: 2rpx solid #ffade1;
      border-radius: 28rpx;
      margin-bottom: 16rpx;
      font-size: 22rpx;
      box-sizing: border-box;
      padding: 6rpx;
      position: relative;

      // 移动的粉色色块
      &::after {
        content: "";
        width: 88rpx;
        height: 44rpx;
        background-color: #ffade1;
        border-radius: 22rpx;
        box-sizing: border-box;
        position: absolute;
        top: 0;
        bottom: 0;
        left: calc(6rpx + (var(--index) * 97rpx));
        margin: auto;
        transition: left 0.45s;
      }

      .option_per {
        width: 88rpx;
        height: 44rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        box-sizing: border-box;
        position: relative;
        z-index: 2;
        color: transparent;
        // 从左向右渐变背景色
        background-image: linear-gradient(
          to right,
          #ffade1,
          #ffade1 50%,
          white 50%,
          white 100%
        );
        -webkit-background-clip: text;
        background-position-x: calc(
          22rpx + var(--index) * 44rpx
        ); // --index 在 computed 内 我挂载到了 页面根标签上 :style="centerCssVariable"
        transition: background-position 0.3s; // 设置过渡动画 (keyframes 相比较更麻烦)

        &:nth-child(1) {
          // 第一个 @我 从左向右渐变
          background-image: linear-gradient(
            to left,
            #ffade1,
            #ffade1 50%,
            white 50%,
            white 100%
          );
        }
      }
    }
  • 上面贴了所有的实现代码,比较关键的代码也加上了注释,copy走可以看效果,感觉实现方式还不是最优解,粉色滑块的移动和文字的颜色渐变并不是同步的 同步的计算有难度就放弃了,如果有更好的实现方法希望可以在下方评论中留言指导