鼠标悬停时的键控和多个功能中的变量

时间:2017-07-21 02:15:38

标签: javascript jquery variables mouseover keydown

当光标移动时," A"密钥被保留,我想要设置一个变量标志。

$(document).on("mousemove", function () {
    $(document).keydown(function(e) {
        if(e.which == 65){
            var $mLeft = '3px',
                $mTop = event.pageY - $sidebarRightDisp;
        } else {
            var $mLeft = event.pageX - $sidebarLeftDisp,
            $mTop = event.pageY - $sidebarRightDisp;
        }
    });
    var $boxStyleAct = 'left:' + $mLeft + 'px;top:' + $mTop + 'px' + ';';
    var $boxAct = '<li style="' + $boxStyleAct + '"></li>';

    $(".boxes").append($boxAct);
});

顺便说一下,我真的不能把我的&#34; //用x&#34;做点什么在keydown函数内部。

非常感谢。

2 个答案:

答案 0 :(得分:0)

您的x变量是在if语句的范围内定义的。你可以把它移出去。你还在mousemove上添加了一个不好的事件监听器。

你可以改为做这样的事情。

var aPressed = false;
var keyPressed = false;
var sidebarRightDisp = 5;
var sidebarLeftDisp = 5;

$(document).mousemove(function(event) {
  if (!keyPressed)
    return;

  var mLeft, mTop;
  if (aPressed) {
    mLeft = '3px';
    mTop = event.pageY - sidebarRightDisp;
  } else {
    mLeft = event.pageX - sidebarLeftDisp;
    mTop = event.pageY - sidebarRightDisp;
  }

  var boxStyleAct = 'left:' + mLeft + 'px;top:' + mTop + 'px' + ';';
  var boxAct = '<li style="' + boxStyleAct + '"></li>';

  $(".boxes").append(boxAct);

}).keydown(function(e) {
  keyPressed = true;
  aPressed = e.which == 65;

}).keyup(function(e) {
  keyPressed = false;
  aPressed = false;

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="boxes">
</div>

答案 1 :(得分:0)

试试这个

&#13;
&#13;
var AkeyPressed = false;
var status = document.getElementById('status');

$(document).on('mousemove', function() {
  if(AkeyPressed == true) {
    console.log("mouse moving while pressing A key");
  }
  else {
    console.log("A key not pressed ");
  }
});
$(document).keydown(function(e) {
  if(e.which == 65) {
    AkeyPressed = true;
    //var x = true;
  }
  else {
    AkeyPressed = false;
    //var x = false;
  }
});
$(document).keyup(function(e) {
  AkeyPressed = false;
});
window.focus();
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
&#13;
&#13;
&#13;