【问题标题】:JavaScript preventDefault is delayed/not working when app is deployed on a network当应用程序部署在网络上时,JavaScript preventDefault 延迟/不起作用
【发布时间】:2021-04-07 18:06:23
【问题描述】:

我有一个带有自定义上下文菜单的应用程序,右键单击时会显示这些菜单。发生这种情况时,我不希望出现默认的 Windows 菜单。我使用以下代码来实现:

            // right click
if (e.which == 3) {
    let menuVisible = false;
    const toggleMenu = command => {
        menu.style.display = command === "show" ? "block" : "none";
        menuVisible = !menuVisible;
    };
    const setPosition = ({ top, left }) => {
        menu.style.left = `${left}px`;
        menu.style.top = `${top}px`;
        toggleMenu("show");
    };
    const origin = {
        left: e.pageX,
        top: e.pageY
    };
    setPosition(origin);
    // toggle right clicked menu visibility
    window.addEventListener("click", e => {
        if (menuVisible) toggleMenu("hide");
    });
    // Set up an event handler for the document right click
    document.addEventListener("contextmenu", function (event) {
        // Only do something when the element that was actually right-clicked
        if (event.target.classList.contains("menu")) {
            event.preventDefault();
        }
    });
}

当应用程序在本地主机上运行时,一切都按预期工作。 但是,当应用程序部署在网络服务器上,然后从网络上的任何客户端访问时,默认菜单首先出现,然后自定义菜单显示在其后面。没有任何错误。 任何有关如何解决此问题的建议将不胜感激。

更新:似乎如果按住鼠标右键不只是单击,则行为符合预期。

【问题讨论】:

  • 您确定代码正在运行吗?
  • JavaScript 在客户端而不是服务器上运行。无论从哪里下载代码,它都应该执行相同的操作。
  • 1.在控制台中运行事件设置代码并检查。如果可行,则 2. 通过点击 Ctrl + F5 并检查来清除网页的浏览器缓存。
  • @goryef,看起来好像您在另一个事件处理程序注册了点击和上下文菜单事件处理程序。您不能将这些移出事件处理程序回调吗?否则,这些将在每次点击时一次又一次地注册,这也解释了为什么最初显示本机菜单。您只需要注册这些一次
  • @ĐinhCarabus。我会调查的。谢谢

标签: javascript contextmenu preventdefault


【解决方案1】:

我认为你必须这样做:

let menuVisible = false;

const toggleMenu = command => {
  menu.style.display = command === "show" ? "block" : "none";
  menuVisible = !menuVisible;
};

const setPosition = ({ top, left }) => {
  menu.style.left = `${left}px`;
  menu.style.top = `${top}px`;
};

// Set up an event handler for the document right click
document.addEventListener("contextmenu", function (e) {
  if (e.target.classList.contains("menu")) {
    e.preventDefault();
    setPosition({
      left: e.pageX,
      top: e.pageY
    });
    toggleMenu("show");
  }
});

// Hide menu
document.addEventListener("click", function(e) {
  if (e.target.classList.contains("menu-item")) {
    alert("menu item was clicked");
  }
  toggleMenu("hide"); 
});
#menu {
  position: absolute;
  padding: 10px;
  background: #eee;
  list-style-type: none;
}
<ul id="menu" style="display:none;">
  <li class="menu-item">Item 1</li>
  <li class="menu-item">Item 2</li>
  <li class="menu-item">Item 3</li>
</ul>

<button class="menu">toggle menu on right click</button>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-02
    • 1970-01-01
    • 2013-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多