如何让自定义CSS模态框内滚动div每次打开时滚动条置顶?
问题:模态框打开时内部滚动div的滚动条无法回到顶部
我自定义了一个CSS模态框,模态框内包含一个可滚动div(模态框本身不可滚动)。首次打开模态框时,div的滚动条正常处于顶部;但滚动后关闭模态框,再次打开时滚动条会停留在之前的位置,我希望每次打开模态框时该div的滚动条都能回到顶部。
现有代码
模态框CSS
.create-modal-content { position: relative; background-color: #F7F7F8; margin: auto; padding: 0; border: 1px solid #888; width: 95%; height: 95%; border-radius: 5px; box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19); animation-name: createAnimation; } @keyframes createAnimation { from { right: 0; opacity: 0 } to { right: 0; opacity: 1 } }
可滚动div CSS
.create-container { background-color: #e7e7e7; margin: 35px 15px 0 15px; border-radius: 10px; max-height: 70vh; overflow: auto; }
HTML结构
<div class="create-modal-content" > <div class="ml-12 mt-24 font-size-18 font-weight-700">Create Organization</div> <div fxLayout="row wrap" fxLayout.xs="column" fxLayoutGap="15px" class="pl-48 pt-12 pb-12 create-container"> <input type="file" accept="image/*" hidden #fileInput (change)="imageSelected($event )" /> </div> <div fxLayout="column" fxLayoutAlign="end center"> <button class="mt-12 mb-12" mat-raised-button color="accent" (click)="saveOrganization()"> Edit </button> </div> </div>
之前尝试无效的TypeScript代码
const modal = document.getElementById('organization'); modal.style.display = 'block'; const createContainer = modal.getElementsByClassName('create-container')[0]; // const createContainer = modal.querySelector(".create-container"); modal.addEventListener('click', function() { createContainer.scrollTop = 0; });
问题分析
之前的代码逻辑错误:把滚动条重置操作绑定在了模态框的click事件上,只有点击模态框时才会触发,但打开模态框的瞬间并没有触发这个事件,所以滚动条依然停留在之前的位置。正确的时机应该是在模态框显示的那一刻就执行滚动条重置。
解决方案
原生JavaScript修正版
直接在打开模态框后立即设置滚动条位置:
const modal = document.getElementById('organization'); modal.style.display = 'block'; // 获取滚动容器并重置滚动条 const createContainer = modal.querySelector('.create-container'); if (createContainer) { createContainer.scrollTop = 0; }
Angular项目推荐方案(适配你的代码环境)
因为你的代码使用了Angular Material(mat-raised-button)和Flex-Layout(fxLayout),更推荐用Angular的ViewChild来获取元素:
- 给滚动容器添加模板引用变量:
<div fxLayout="row wrap" fxLayout.xs="column" fxLayoutGap="15px" class="pl-48 pt-12 pb-12 create-container" #scrollContainer>
- 在组件类中获取元素并在打开模态框时重置:
import { ViewChild, ElementRef } from '@angular/core'; // 组件类内部 @ViewChild('scrollContainer') scrollContainer!: ElementRef<HTMLDivElement>; // 打开模态框的方法 openModal() { const modal = document.getElementById('organization'); modal.style.display = 'block'; // 使用setTimeout确保DOM已渲染完成(或用Angular变更检测钩子) setTimeout(() => { this.scrollContainer.nativeElement.scrollTop = 0; }, 0); }
如果使用Angular CDK模态框组件,可以直接在afterOpened钩子中执行重置操作,无需手动处理DOM显示时机。
内容的提问来源于stack exchange,提问作者Mezbaul Islam Aunik
相关产品推荐
相关产品推荐

