Shift + mouseover with jQuery

吃可爱长大的小学妹 提交于 2019-12-12 08:29:52

问题


I'm trying to detect whether the shift key is being pressed while the cursor is moved over a particular element. The function fires, but only after I click on another element first. Is there some way to work around this? I've tried setting focus to both the document and element, and tried creating a pseudo-click function but so far nothing has worked.

For example, the following code works only after I click another element on the page:

$("#selector").mouseover(function(e){
    if(e.shiftKey) {
        console.log("the shift key is pressed");
    }
});

Thanks in advance for any information.


回答1:


check this on the keypress event:

$(document).keypress(function (e) {

  if(e.shiftKey) {
    pressed = true; // pressed is a global varialbe. Be carefull of the scope
  }

}

then on the keyup:

$(document).keyup(function(event){
   pressed = false;
});

then do:

$("#selector").mouseover(function(e){
    if(pressed) {
        console.log("the shift key is pressed");
    }
});

or the other way around :

$("#selector").mouseover(function(e){
    isover = true;
});

and

   $(document).keypress(function (e) {

      if(e.shiftKey) {
        alert("do something")
      }

   }



回答2:


It is not necessary to store in a variable when the shift key is pressed and released. You can achieve what you are trying to to like this:

$('#selector').mouseover(
    function(e){
        if (e.shiftKey)
        {
            console.log("the shift key is pressed");
        }
    }
);



回答3:


I tried your code like this and it works perfectly. You do have to "shift" then mouseover, though.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script>
    loadHandler = function(){
        $("#selector").mouseover(function(e){
            if(e.shiftKey) {
                alert("the shift key is pressed");
            }
        });
    }
</script>
</head>
<body onload="loadHandler();">
<div style="border:1px solid black" id="selector">

    <br/>
    <br/>

    This is a div.

    <br/>
    <br/>

<div>
</body>
</html>

What type of element is it being applied to?




回答4:


Working sample,

MouseEvent.shiftKey, MouseEvent.ctrlKey

MouseEvent.ctrlKey

MouseEvent.shiftKey

   <img onmouseover="keypress_test(event)" onmouseout="keypress_test(event)">


    function keypress_test(event) {

             // false, no press, 
             // true, pressed

              console.log(event.ctrlKey)

              console.log(event.shiftKey)
       }


来源:https://stackoverflow.com/questions/1441086/shift-mouseover-with-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!