单击第一个菜单项后防止 MDC 菜单关闭

Prevent MDC Menu from closing after clicking first menu item

我们正在使用 MDC 菜单组件。我正在寻找一种在单击菜单中的第一项时不关闭菜单的方法。

我尝试将 class 应用于 mdc-list-item 并将光标指定为自动,但它不起作用。

.menu-do-not-close {
   cursor: auto !important;
}

下面是例子fiddle

https://jsfiddle.net/phani25485/Lt6q2gxa/2/

您能否就如何实现这一点提供一些指导。

当事件目标分配了特定 class 时,您可以通过在 mdc-list-item 单击事件上调用 event.stopPropagation() 来阻止菜单在选择特定项目后关闭。您将需要添加一些额外的代码来处理列表项点击事件,因为这会阻止正常的 MDC menu 点击处理。

const menu = mdc.menu.MDCMenu.attachTo(document.querySelector('.mdc-menu'));
document.querySelector('.mdc-button').addEventListener('click', () => {
  menu.open = !menu.open;
});

//Prevent menu close when option with 'prevent-menu-close' class clicked
for (const option of document.querySelectorAll('.mdc-list-item')) {
  option.addEventListener('click', (event) => {
    const prevent = event.currentTarget.classList.contains('prevent-menu-close');
    if (prevent) {
      event.stopPropagation();
      // handle 'prevent-menu-close' list item click event
    }
  });
}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Material Select</title>
    <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700">
    <link href="https://unpkg.com/material-components-web@latest/dist/material-components-web.min.css" rel="stylesheet">
    <script src="https://unpkg.com/material-components-web@latest/dist/material-components-web.min.js"></script>
  </head>
  <body>
    <div class="mdc-menu-surface--anchor">
      <button class="mdc-button">
        <span class="mdc-button__label">Open Menu</span>
      </button>
      <div class="mdc-menu mdc-menu-surface">
        <ul class="mdc-list" role="menu" aria-hidden="true" aria-orientation="vertical" tabindex="-1">
          <li class="mdc-list-item prevent-menu-close" role="menuitem">
            <span class="mdc-list-item__text">Prevent Close</span>
          </li>
          <li class="mdc-list-item" role="menuitem">
            <span class="mdc-list-item__text">Another Menu Item</span>
          </li>
        </ul>
      </div>
    </div>
  </body>
</html>