css 如何在打开材质菜单时保持图像样式

hts6caw3  于 2022-11-19  发布在  其他
关注(0)|答案(1)|浏览(148)

我已经添加了一个弹出动画到一个图像,每当用户悬停在图像上。该图像也有一个自定义的上下文菜单。效果工作的预期悬停,但会消失,只要上下文菜单是通过右键单击图像启动。我需要的效果,即使在上下文菜单启动。我该如何做呢?提前感谢您的帮助。
模板代码:

<image class="image" (contextmenu)="onContextMenu($event)" href="assets/images/USER.png" width="150" height="135" image-rendering="optimizeQuality" preserveAspectRatio="none" />
    
<div
  id="contextMenu"
  style="visibility: hidden; position: fixed"
  [style.left]="contextMenuPosition.x"
  [style.top]="contextMenuPosition.y"
  [matMenuTriggerFor]="contextMenu"
></div>

<mat-menu #contextMenu="matMenu">
  <ng-template matMenuContent let-item="item">
    <button mat-menu-item (click)="onContextMenuAction1(item)">Action 1</button>
    <button mat-menu-item (click)="onContextMenuAction2(item)">Action 2</button>
  </ng-template>
</mat-menu>

CSS:

.image {
    transform: scale(1, 1);
    transition: transform 0.2s ease-in;
  }

  .image:hover {
    transform: scale(1.05, 1.05);
  }

技术支持:

@ViewChild(MatMenuTrigger)
  contextMenu: MatMenuTrigger;

  contextMenuPosition = { x: '0px', y: '0px' };

  ngOnInit() {}

  onContextMenu(event: MouseEvent, item?: Item) {
    event.preventDefault();
    this.contextMenuPosition.x = event.clientX + 'px';
    this.contextMenuPosition.y = event.clientY + 'px';
    this.contextMenu.menuData = { item: item };
    this.contextMenu.menu.focusFirstItem('mouse');
    this.contextMenu.openMenu();
  }

  onContextMenuAction1(item: Item) {
    alert(`Click on Action 1 for ${item.name}`);
  }

  onContextMenuAction2(item: Item) {
    alert(`Click on Action 2 for ${item.name}`);
  }
}

 export interface Item {
   id: number;
   name: string;
 }
7d7tgy0s

7d7tgy0s1#

首先,使用<img>代替<image><image>元素shouldn't be used
播放mat-menumenuClosedmenuOpened事件
当菜单打开时,向图像中添加一个具有相同样式的类,并在菜单关闭时删除该类。
CSS

.image {
  transform: scale(1, 1);
  transition: transform 0.2s ease-in;
}

.image:hover,
.image-clicked-hover {
  transform: scale(1.05, 1.05);
}

时间

menuClosed($event) {
    console.log('Menu is closed');
    var imageHtmlElement = document.getElementById('image');
    imageHtmlElement.classList.remove('image-clicked-hover');
  }

menuOpened($event) {
    console.log('Menu is opened');
    var imageHtmlElement = document.getElementById('image');
    imageHtmlElement.classList.add('image-clicked-hover');
  }

Demo

相关问题