迹忆客 专注技术分享

当前位置:主页 > 学无止境 > WEB前端 > JavaScript >

JavaScript 右键菜单

作者:迹忆客 最近更新:2024/03/20 浏览次数:

上下文菜单是一种约定,允许我们创建自定义右键菜单。

右键单击菜单是单击鼠标右键时预览的简单面板。菜单的这些选项可以有不同的功能发挥。


使用 oncontextmenu 事件启用 JavaScript 右键菜单

每次确保右键单击时,oncontextmenu 事件将启用动态创建 div 元素。

我们将为菜单定位设置样式。如果我们不设置事件派生位置,菜单将在页面的一部分上是静态的。

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Test</title>
  <style>
#contextMenu {
  position: fixed;
  background:teal;
  color: white;
  cursor: pointer;
  border: 1px black solid
}
#contextMenu > p {
  padding: 0 1rem;
  margin: 0
}
#contextMenu > p:hover {
  background: black;
  color: white;
}
</style>
</head>
<body>
  <script>
  oncontextmenu = (e) => {
  e.preventDefault()
  var menu = document.createElement("div")
  menu.id = "contextMenu"
  menu.style = `top:${e.pageY-10}px;left:${e.pageX-40}px`
  menu.onmouseleave = () => contextMenu.outerHTML = ''
  menu.innerHTML = "<p onclick='alert(`1 It is!`)'>Choose 1</p><p onclick='alert(`2 It is!`)'>Choose 2</p><p onclick='alert(`3 It is!`)'>Choose 3</p><p onclick='alert(`Thank you!`)'>No thanks</p>"
  document.body.appendChild(menu)
}
  </script>
</body>
</html>

输出:

oncontextmenu 事件中,我们设置 onmouseleave 事件以使选项框在光标从菜单中移除时消失。

选择一个选项时,我们将在 Windows 警报中获得所需的输出。这是在右键单击时创建上下文菜单的方法。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Do you understand JavaScript closures?

发布时间:2025/02/21 浏览次数:108 分类:JavaScript

The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.

Do you know about the hidden traps in variables in JavaScript?

发布时间:2025/02/21 浏览次数:178 分类:JavaScript

Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av

How much do you know about the Prototype Chain?

发布时间:2025/02/21 浏览次数:150 分类:JavaScript

The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start

用 jQuery 检查复选框是否被选中

发布时间:2024/03/24 浏览次数:102 分类:JavaScript

在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便