将元素滚动到浏览器窗口的可见区域scrollIntoView

71 阅读1分钟
  • 使用方法
element.scrollIntoView(
  { 
    behavior: "auto", // smooth-平滑
    block: "center", // 垂直方向的对齐方式 start  center  end nearest
    inline: "start", // 控制水平方向的对齐方式 start  center  end nearest
  }
)
  • 示例
<template>
  <van-steps 
    v-model:active="activeStep" 
    ref="stepsRef"
    @click-step="handleStepClick"
  >
    <van-step>步骤1</van-step>
    <van-step>步骤2</van-step>
    <van-step>步骤3</van-step>
  </van-steps>
</template>

<script setup>
import { ref } from 'vue';

const activeStep = ref(0);
const stepsRef = ref(null);

// 点击步骤时滚动到对应节点
const handleStepClick = (index) => {
  activeStep.value = index;
  scrollToActiveStep();
};

// 滚动到当前激活的步骤
const scrollToActiveStep = () => {
  nextTick(() => {
    const activeStepNode = stepsRef.value?.$el.querySelector('.van-step--process');
    if (activeStepNode) {
      activeStepNode.scrollIntoView({
        behavior: 'smooth',  // 平滑滚动
        block: 'center',     // 垂直居中
        inline: 'nearest'    // 水平对齐
      });
    }
  });
};
</script>