gpt4 book ai didi

javascript - 我应该监听哪些事件以在 JavaScript 中隐藏自定义上下文菜单

转载 作者:行者123 更新时间:2023-11-29 20:53:32 26 4
gpt4 key购买 nike

我想知道我应该监听哪些事件来隐藏我的自定义上下文菜单,一个 <div>oncontextmenu 中显示的元素事件处理程序,就像在 native 中一样。

最佳答案

有多种关闭 native 上下文菜单的操作:

这是一个简单的示例,其中包含我提到的一些选项:

const contextMenu = document.getElementById('contextMenu');
const MARGIN = 10;

document.oncontextmenu = (e) => {
e.preventDefault();

const target = e.target;

if (contextMenu === target || contextMenu.contains(target)) {
// A right-click on the context menu itself (or anything inside it) will NOT reposition it:
return;
}

contextMenu.style.left = `${ Math.min(window.innerWidth - contextMenu.offsetWidth - MARGIN, Math.max(MARGIN, e.clientX)) }px`;
contextMenu.style.top = `${ Math.min(window.innerHeight - contextMenu.offsetHeight - MARGIN, Math.max(MARGIN, e.clientY)) }px`;

contextMenu.classList.remove('hidden');
};

contextMenu.onmousedown = (e) => {
// We don't want this click to close the context menu, so we stop its propagation:
e.stopPropagation();
};

// EVENTS THAT CLOSE THE CONTEXT MENU:

window.onblur = () => {
contextMenu.classList.add('hidden');
};

document.onmousedown = () => {
contextMenu.classList.add('hidden');
};

document.onmousewheel = () => {
contextMenu.classList.add('hidden');
};

document.onkeydown = (e) => {
if (e.key === 'Escape' || e.which === 27 || e.keyCode === 27) {
contextMenu.classList.add('hidden');
}
};
html,
body {
height: 100%;
}

body {
display: flex;
justify-content: center;
align-items: center;
margin: 0;
font-family: monospace;
}

#contextMenu {
box-sizing: border-box;
padding: 5px;
width: 200px;
min-height: 50px;
max-height: calc(100vh - 20px);
background: white;
position: fixed;
border-radius: 2px;
box-shadow: 0 0 32px rgba(0, 0, 0, .25);
transition: box-shadow ease-in 50ms;
}

#contextMenu:hover {
box-shadow: 0 0 48px rgba(0, 0, 0, .25);
}

#contextMenu:active {
box-shadow: 0 0 16px rgba(0, 0, 0, .25);
}

#contextMenuImage {
width: 100%;
border-radius: 2px;
display: block;
}

.hidden {
visibility: hidden;
}
<div id="contextMenu" class="hidden">
<img id="contextMenuImage" src="https://media1.giphy.com/media/3o7aTskHEUdgCQAXde/giphy.gif" />
</div>

RIGHT-CLICK TO SEE THE CONTEXT MENU

请注意,在 oncontextmenu 处理程序中还有一个检查,以防止右键单击上下文菜单本身重新定位它。

关于javascript - 我应该监听哪些事件以在 JavaScript 中隐藏自定义上下文菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50538072/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com