JS事件CTRL+鼠标悬停+隐藏文本

JS Event CTRL + mouse over + hide text

本文关键字:隐藏 文本 悬停 鼠标 事件 CTRL+ JS      更新时间:2024-01-19

我必须实现这一点:

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

到目前为止我的工作:

<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script>
    loadHandler = function(){
        $("#selector").mouseover(function(e){
            if(e.ctrlKey) {
                //what do I have to write here so that holding CTRL will be recognized ?
            }
        });
    }
</script>
</head>
<body onload="loadHandler();">
<button type="button" onmouseover="document.getElementById('center').style.visibility = 'visible'">CTRL+mouseover</button>
<div id="center" onmouseout="this.style.visibility = 'hidden'">
        <h1>Text text text</h1>
</div>
</body>
</html>

链接

我不得不承认,我刚开始学习JS,所以请帮帮我:)

  • 如何使按住CTRL键和鼠标同时被识别

工作样本,

MouseEvent.shiftKey、MouseEvent.ctrlKey

鼠标事件.ctrlKey

鼠标事件移动键

   <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)

             if (event.ctrlKey) {
                    // hide text
                }
       }

完美工作版本

$(document).ready(function(){
    var keyPressed = false;
    var mouseovered = false;
    $("#center").mouseover(function(e){
      doStuff();
         mouseovered = true;
    });
    $("#center").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"});
    }
});

我只是默认情况下没有隐藏文本。否则你很难找到它现在的位置。在检查之前,不要忘记点击body。否则将不会检测到keypress

工作Fiddle