angular框架的画面。
现状是主页面点击检索按钮后,下边会显示很多检索结果项目,同时会出现纵滚动条。
向下移动纵滚动条到页面下边的某处,点击按钮打开的模态窗口会自动显示在整个主画面的最顶端的中央(纵滚动条自动跳到最开始了)。
但希望能打开的窗口不跳到最上边显示,而是动作在哪个位置的页面,就弹出显示在那个页面的相对顶端中央。也就是说,滚动条不滚到最上边。
请问如何实现呢?需要同时兼容IE和chrome。
※设CSS的position么?在那儿怎么设置呢?
angular框架的画面。
现状是主页面点击检索按钮后,下边会显示很多检索结果项目,同时会出现纵滚动条。
向下移动纵滚动条到页面下边的某处,点击按钮打开的模态窗口会自动显示在整个主画面的最顶端的中央(纵滚动条自动跳到最开始了)。
但希望能打开的窗口不跳到最上边显示,而是动作在哪个位置的页面,就弹出显示在那个页面的相对顶端中央。也就是说,滚动条不滚到最上边。
请问如何实现呢?需要同时兼容IE和chrome。
※设CSS的position么?在那儿怎么设置呢?
要实现打开的窗口显示在指定位置的相对顶端中央,可以使用 CSS 的 position
属性和 top
、left
属性来控制窗口的位置。具体实现步骤如下:
position
属性为 relative
,这样子容器的位置可以相对于父容器进行定位。top
和 left
属性值,使其显示在指定位置的相对顶端中央。具体的代码实现可能会因为页面的具体结构和样式而有所不同,但大致的代码实现如下:
HTML:
<div class="main">
<!-- 主页面内容 -->
<button (click)="openModal()">打开模态窗口</button>
<div class="result">
<!-- 检索结果 -->
</div>
</div>
<div class="modal-parent" #modalParent>
<div class="modal-placeholder" #modalPlaceholder></div>
<div class="modal" [style.top.px]="modalTop" [style.left.px]="modalLeft">
<!-- 模态窗口内容 -->
</div>
</div>
CSS:
.modal-parent {
position: fixed;
top: 0;
left: 0;
z-index: 9999;
width: 100%;
height: 100%;
overflow: hidden;
}
.modal-placeholder {
/* 占位元素,根据需要的位置进行设置 */
position: absolute;
top: 200px;
left: 200px;
width: 0;
height: 0;
}
.modal {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
/* 模态窗口样式 */
}
TypeScript:
import { Component, ElementRef, ViewChild } from '@angular/core';
@Component({
selector: 'app-root',
template: `<!-- 主页面模板 -->`,
styleUrls: ['./app.component.css']
})
export class AppComponent {
@ViewChild('modalParent') modalParentRef: ElementRef;
@ViewChild('modalPlaceholder') modalPlaceholderRef: ElementRef;
modalTop: number;
modalLeft: number;
openModal(): void {
// 获取占位元素的位置
const modalPlaceholderEl = this.modalPlaceholderRef.nativeElement;
const modalPlaceholderRect = modalPlaceholderEl.getBoundingClientRect();
// 计算模态窗口的位置
const modalParentEl = this.modalParentRef.nativeElement;
const modalParentRect = modalParentEl.getBoundingClientRect();
this.modalTop = modalPlaceholderRect.top - modalParentRect.top + modalParentEl.scrollTop + modalPlaceholderEl.offsetHeight / 2;
this.modalLeft = modalPlaceholderRect.left - modalParentRect.left + modalParentEl.scrollLeft + modalPlaceholderEl.offsetWidth / 2;
}
}
上面的代码中,使用了 ElementRef
和 ViewChild