javascript - 如何关闭鼠标左键窗口?
问题描述
我有一些弹出窗口,现在如果我按下任何鼠标按钮它们就会关闭。我只需要鼠标左键按下并关闭弹出窗口
第二个问题。为什么 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');
}
}
解决方案
这是有关鼠标单击事件的有用文档 https://www.w3schools.com/jsref/event_button.asp
您可以在“mousedown”事件上添加事件侦听器并检查是否event.button
等于 0。
UPD
您只需要if
在事件处理程序中添加条件
editPopup.addEventListener('mousedown', (evt) => {
if (evt.button === 0) {
overlayClose(evt);
}
});
推荐阅读
- javascript - Sinon Spy 从未打过电话,但应该打
- c# - 将数据从局部视图传递到父视图
- amazon-web-services - 使用 AWS Toolkit 创建项目后直接在 pom.xml 文件中出错
- sql - 从 Sql 表中的单个 Id 中选择多个 Itme
- excel - 如何从导入的文件中删除重复项?
- python - 长正则表达式替换需要多次通过才能完成 - 为什么?
- python - 尝试生成虚拟 DataFrame 但出现错误
- c# - 创建一个 EntryPoint.Invoke(null, null); 在 MethodInfo 下并调用它
- groovy - 在声明性 Jenkins 管道中存储环境变量中的值列表
- mysql - 逐一获取列数据