网站搜索

angular - 在屏幕上保留右键菜单


我为我的上下文菜单创建了一个 TypeScript 组件,一切工作正常,除了当上下文菜单在屏幕边缘被激活时,它会超出屏幕边缘,导致部分项目无法访问。

这是我的上下文菜单的 HTML 结构

<div id="contextMenu">
  <div
    class="menu-link"
    *ngFor="let menuItem of contextMenuItems; index as i"
    (click)="onContextMenuClick($event, menuItem.menuEvent)">
    <div *ngIf="menuItem.menuText !== 'divider'">{{ menuItem.menuText }}</div>
    <hr *ngIf="menuItem.menuText == 'divider'" />
  </div>
</div>

菜单项是根据“上下文”动态添加的

右键点击激活此代码

displayContextMenu(event) {
this.myContextMenuService.buildMenu();
this.rightClickMenuPositionX = event.clientX;
this.rightClickMenuPositionY = event.clientY;
}

我尝试过几种 CSS 方法,但无论从哪里激活,整个菜单都无法保持在屏幕上。

答案#1

displayContextMenu(event) {
  this.myContextMenuService.buildMenu();
  // get your contextMenu width and height
  const contextMenu = document.getElementById('contextMenu');
  const contextMenuWidth = contextMenu.offsetWidth;
  const contextMenuHeight = contextMenu.offsetHeight;

  const xPos = event.clientX + contextMenuWidth > window.innerWidth ? window.innerWidth - contextMenuWidth : event.clientX;
  const yPos = event.clientY + contextMenuHeight > window.innerHeight ? window.innerHeight - contextMenuHeight : event.clientY;

  this.rightClickMenuPositionX = xPos;
  this.rightClickMenuPositionY = yPos;
}

答案#2

为什么要让这件事比原本更难?使用 Angular 的 Cdk,它开箱即用处理这个问题。没必要重新发明轮子。