Shift + mouseover with jQuery

前端 未结 4 1258
再見小時候
再見小時候 2021-02-20 13:34

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

相关标签:
4条回答
  • 2021-02-20 13:52

    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");
            }
        }
    );
    
    0 讨论(0)
  • 2021-02-20 13:54

    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)
           }
    
    0 讨论(0)
  • 2021-02-20 14:01

    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")
          }
    
       }
    
    0 讨论(0)
  • 2021-02-20 14:12

    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?

    0 讨论(0)
提交回复
热议问题