首页 > 解决方案 > 如何关闭鼠标左键窗口?

问题描述

我有一些弹出窗口,现在如果我按下任何鼠标按钮它们就会关闭。我只需要鼠标左键按下并关闭弹出窗口

第二个问题。为什么 esc 弹出代码不起作用?

    const overlayClose = (evt) => {
        if (evt.target.classList.contains('popup_active')) {
            togglePopup(evt.target);
        }
    }
    editPopup.addEventListener('mousedown', (evt) => {
        overlayClose(evt);
    });
    addPopup.addEventListener('mousedown', (evt) => {
        overlayClose(evt);
    });
    imagePopup.addEventListener('mousedown', (evt) => {
        overlayClose(evt);
    });
    
    
    //popup esc code
function togglePopup(popup) {
    popup.classList.toggle('popup_active');
    if (popup.classList.contains('popup_active')) {
        document.addEventListener('keydown', closeEscape);
    } else {
        document.removeEventListener('keydown', closeEscape);
    }
}


const closeEscape = (evt) => {
    if (evt.key === "Escape") {
        popup.classList.remove('popup_active');
    }
}

标签: javascript

解决方案


这是有关鼠标单击事件的有用文档 https://www.w3schools.com/jsref/event_button.asp

您可以在“mousedown”事件上添加事件侦听器并检查是否event.button等于 0。

UPD

您只需要if在事件处理程序中添加条件

 editPopup.addEventListener('mousedown', (evt) => {
    if (evt.button === 0) {
      overlayClose(evt);
    }
 });

推荐阅读