scrollIntoView:让页面滚动到指定元素的可见区域

 目的:点击左侧树结构  右侧相应的内容滚动到可视范围内

 

页面部分

左侧是 Ant Design Vue 的 Tree 组件,右侧是内容区域,包含了多个部分,每个部分都有一个唯一的 id(如 section1section2 等)。当左侧目录树的某个节点被点击时,会获取到对应的部分 id,并通过 scrollIntoView() 方法实现平滑滚动效果,将该部分滚动到顶部。

//页面部分

<a-card>
      <div class="overall">
        <!-- 左侧 -->
        <div class="overall_side">
          <a-directory-tree
            v-model:expandedKeys="expandedKeys"
            v-model:selectedKeys="selectedKeys"
            :tree-data="treeData"
            @select="handleTreeSelect"
          ></a-directory-tree>
        </div>

        <!-- 右侧主体 -->
        <div class="overall_main">
            <!-- 根据处理好的treeData数据 循环出右侧内容 -->
          <div v-for="(item, index) in treeData" :key="index">
            <!-- 右侧每一大块的标题  也绑定id 点击左侧树结构的父节点 右侧对应的大标题也出现在可视范围-->
            <div class="title" :id="item.key">{{ item.title }}</div>
            <!-- 每一大块的item -->
            <a-card hoverable class="main_item">
              <!-- 循环children -->
              <div v-for="child in item.children" :key="child.key" class="main_conter">
                <!-- 绑定id  用于左侧点击后 对应id的右侧内容出现在屏幕的可视范围 -->
                <div class="section" :id="child.key">
                  <div>{{ child.title }}</div>
                  <a-input
                    v-model:value="child.value"
                    @focus="handleFocus(child)"
                    @blur="handleBlur(child.value)"
                    class="section_title"
                    placeholder="请输入参数"
                  />
                </div>
              </div>
            </a-card>
          </div>
        </div>
      </div>
    </a-card>

 

 handleTreeSelect 树结构点击

 sectionElement.scrollIntoView

// 处理目录树点击事件
const handleTreeSelect = (sectionId: string, info: any) => {
  const sectionElement = document.getElementById(sectionId);
  if (sectionElement) {
    sectionElement.scrollIntoView({ behavior: 'smooth', block: 'start' });
  }
};

 

scrollIntoViewOptions 可选  一个包含下列属性的对象:

behavior:用于指定滚动的行为,默认值为"auto"。可以设置为"auto"、"smooth"或者"instant"。其中,"auto"表示浏览器自动选择滚动方式,"smooth"表示平滑滚动,"instant"表示瞬间滚动。

block:用于指定滚动的垂直方向,默认值为"start"。可以设置为"start"、"center"、"end"或者"nearest"。其中,"start"表示将元素的顶部与可见区域的顶部对齐,"center"表示将元素的中部与可见区域的中部对齐,"end"表示将元素的底部与可见区域的底部对齐,"nearest"表示将元素滚动到可见区域内,如果元素已经在可见区域内,则不进行滚动。

inline:用于指定滚动的水平方向,默认值为"nearest"。可以设置为"start"、"center"、"end"或者"nearest"。其中,"start"表示将元素的左边与可见区域的左边对齐,"center"表示将元素的中部与可见区域的中部对齐,"end"表示将元素的右边与可见区域的右边对齐,"nearest"表示将元素滚动到可见区域内,如果元素已经在可见区域内,则不进行滚动

  • 5
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值