3

I'm trying to make a dynamic javascript menu (contained in a div) appear at a visitor's mouse coordinates when they press ctrl+m on their keyboard (m signifying menu, and ctrl+m not being bound in most browsers as far as I'm aware). This way, wherever they are on my site and wherever their mouse is, they can pull up the menu by just pressing that combination and return to wherever they wish to go. At the same time, having the menu not shown until they press the key allows me to control the design experience completely without having to worry about a nav menu.

I've pulled together two different pieces of code I found on here in an attempt to do this myself, but I'm running into an unexpected issue.

  1. I'm not sure how to denote the ctrl+m key combination in the event handler.
  2. I'm getting a couple of errors on the code checker that I'm not sure how to fix myself.
  3. I'm not sure how to make it so that the menu appears on ctrl+m, and stays there until ctrl+m is pressed again (a toggle switch).

I'm still learning how Javascript works.

Here's the link to the progress I've made so far: http://jsfiddle.net/nrz4Z/

4

2 回答 2

1

在您的示例中,您将处理程序绑定在mousemove处理程序中keypress。您需要单独执行它们:

var mouseX;
var mouseY;
$(document).ready(function () {

    $(document).mousemove(function (e) {
        mouseX = e.pageX;
        mouseY = e.pageY;
    });

    $(document).keypress(function (event) {
        if (event.which == 109) {
            $('#examples').css({
                'top': mouseY,
                'left': mouseX
            }).fadeIn('slow');
        };
    });
});

这应该允许您获得显示菜单的位置。

于 2013-07-31T16:53:31.180 回答
0

首先,使用 keypress 不是一个好主意 - 网络是不可知数量的浏览器、设备和插件上的东西,你不知道哪些快捷方式绑定到特别是使用单个键的修饰符的快捷方式(在这种情况下是 cmd +m 或 ctrl+m 是在许多操作系统上最小化窗口的操作系统快捷方式。 ctrl 在 os x 中以 cmd 的形式存在,而在手机上根本不存在。)

要检测多个按键,请在此处检查:Can jQuery .keypress() 同时检测多个按键吗?

接下来,您可以检测鼠标移动并将它们存储在一个变量中以便在任何地方使用:如何在没有鼠标事件的情况下在 jQuery 中获取鼠标位置?

然后,您的菜单应该位于 DOM 的底部,只有 body 作为它的父级:

<nav>
  <p>My Menu</p>
<nav>
</body>

您的导航应该在 css 中具有所需的任何样式,以及:

nav {
  position: absolute;
  display: none;
  /*z-index: 700; nav is at bottom of dom so it will go above anything without a z-index but you may want it to go over other things */
}

当您检测到按键时,您应该执行以下操作:

$('nav').css({top: mouseYCoord, left: mouseYCoord}).show();

显然给你的菜单一个更有用的名字,不要选择所有的“导航”标签。

于 2013-07-31T16:57:05.380 回答