Javascript事件-同时按住CTRL键和鼠标悬停在按钮上

Javascript Event - Holding CTRL Key and mousover on button at the same time

本文关键字:鼠标 悬停 按钮 CTRL 事件 Javascript      更新时间:2023-12-26

到目前为止,我有两个解决方案,但都不起作用。有人能把我带向正确的方向吗?

我正在努力实现以下目标:

  1. 隐藏div中的文本
  2. 用户将按下Ctrl键,然后将鼠标放在按钮上——必须调用一个javascript函数,并且div中的文本应该显示出来
  3. 如果用户释放Ctrl键-文本应该消失(即使鼠标在按钮上),类似地,如果用户将鼠标从按钮中移出-文本应该会消失(即使按下Ctrl键)

首次尝试:

<html>
    <head>
    <script type="text/javascript" src="js/jquery-2.1.1.min.js"></script>
    <script>
       $(document).ready(function(){
           $("#center").css("visibility","hidden"); //Hidden text in the beginning
            $("#select").mouseover(function(e){
                while(e.ctrlKey) 
                  $("#center").css("visibility","visible");
                $("#center").css("visibility","hidden");     
            }).mouseout(function(){
               $("#center").css("visibility","hidden");
            });
        });   
    </script>
    </head>
    <body>
      <button type="button" id="select">CTRL+mouseover</button>
      <div id="center">
            <h1>Text text text</h1>
      </div>
    </body>
</html>

第二次尝试:

http://jsfiddle.net/o0q5nszz/10/

作为简历,整个代码的想法是在按钮上按住CTRL+鼠标会显示隐藏的文本。有人能把我带向正确的方向吗?

我添加了一个按钮,并在按钮上附加了以前的#鼠标中心事件

看看这个工作小提琴:http://jsfiddle.net/o0q5nszz/11/

$(document).ready(function(){
    $(document).focus();
    var keyPressed = false;
    var mouseovered = false;
    $("#btn").mouseover(function(e){
      doStuff();
         mouseovered = true;
    });
    $("#btn").mouseout(function(){
        doStuff();
        mouseovered = false; 
    });
    $(document).keydown(function(e){
         doStuff();
         if (e.ctrlKey) 
         {
             keyPressed = true;
         }
        else keyPressed = false;
    });
    $(document).keyup(function(e){
         if (keyPressed) 
         {
             keyPressed = false;
         }
        doStuff();
    });
    function doStuff()
    {
        if(mouseovered && keyPressed) $("#center").css({"color": "#000"});
    else  $("#center").css({"color": "#fff"});
    }
});

你可以用旧的方式,但在2019年,你可以用新的方式:

MouseEvent.ctrlKey只读属性是布尔

   <img onmouseover="bigImg(event)" onmouseout="normalImg(event)">

    function bigImg(event) {
             // false if no ctrl key, true, if pressed
              console.log(event.ctrlKey)

       }