admin管理员组文章数量:1430979
I'm blocking context menu, then I want to restore it to previous state.
myElement = document.querySelector('*');
myElement.addEventListener('contextmenu', MyContextMenu);
it is possible to restore default context menu after the above code have been executed ? if the answer is yes then how or how to make it correctly?
what i want is to block context menu and then restore it after a while.
I'm blocking context menu, then I want to restore it to previous state.
myElement = document.querySelector('*');
myElement.addEventListener('contextmenu', MyContextMenu);
it is possible to restore default context menu after the above code have been executed ? if the answer is yes then how or how to make it correctly?
what i want is to block context menu and then restore it after a while.
Share Improve this question asked Nov 6, 2013 at 22:33 user971637user971637 1-
Not sure if i understand your question correctly, but you could call
myElement.removeEventListener('contextmenu', MyContextMenu);
at the time where you don't want to haveMyContextMenu
to be called anymore for the next invocations of the contextmenu. – t.niese Commented Nov 6, 2013 at 22:40
3 Answers
Reset to default 5Reassign all context menus to default:
document.querySelector('div').oncontextmenu = _=>false;
var d = document.createElement('div').oncontextmenu;
[...document.querySelectorAll("*")].forEach(e => e.oncontextmenu = d);
<div>sample</div>
Update
Here is a modern version with the "prevent" concept:
document.querySelector('div').oncontextmenu = e => {
e.preventDefault()
return false
}
const fn = document.createElement('div').oncontextmenu
document.querySelectorAll('*').forEach(el => el.oncontextmenu = fn)
<div>sample</div>
Note: This will not work if the event is assigned as an event listener:
document.querySelector('div')
.addEventListener('contextmenu', e => {
e.preventDefault() // <-- problem
return false
})
const fn = document.createElement('div').oncontextmenu
document.querySelectorAll('*').forEach(el => el.oncontextmenu = fn)
<div>sample</div>
var oldHandlerToKeep = element.oncontextmenu
Here's an alternate solution (based on this post by Chema):
document.body.oncontextmenu = null;
document.addEventListener("contextmenu",
function (event) {
event.returnValue = true;
if (typeof(event.stopPropagation) === 'function')
{
event.stopPropagation();
}
if (typeof(event.cancelBubble) === 'function')
{
event.cancelBubble();
}
}, true);
This helps to restore the context menu if preventDefault()
was previously called. Hopefully it might help some passersby.
本文标签: javascriptIt is possible to Restore context menuStack Overflow
版权声明:本文标题:javascript - It is possible to Restore context menu - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745455142a2659067.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论