在鼠标(指针设备)未处于活动状态(不移动)时隐藏按钮

Hiding a button when mouse (pointing device) is not active (not moving)

本文关键字:活动状态 移动 按钮 隐藏 指针 鼠标      更新时间:2023-09-26

我试图在鼠标不移动时隐藏按钮。就这样。我在这里找到了一个解决方案,但它引用了一个 Google javascript 文件(直接链接到他们的一个托管驱动器上的 javascript 文件(,我希望我的网站不依赖于其他任何东西——我希望它是独立的。

请帮忙!

<html>
  <head>
   <script type="text/javascript">>
  
     function change( el )
     {
       if ( el.value === "Display Menu" )
         el.value = "Hide Menu";
       else
         el.value = "Display Menu";
     }
  
    </script>
   
  </head>
  <body>
    <input type="button" value="Display Menu" onclick="return change(this);" />
  </body>  
</html>

我相信

你找到的解决方案有一个你不想要的jQuery部分。

这是可以的,因为它是纯原生的javascript。

var el =  document.getElementById("btnMenu");
var timer;
function showBtn(){
	el.style.display = "block";
}
function hideBtn(){
	el.style.display = "none";
}
hideBtn();
document.onmousemove = function(){
   showBtn();
   clearTimeout(timer);
   timer = setTimeout(function(){
        hideBtn();
    },100)
}
<body>
    <input id="btnMenu" type="button" value="Display Menu"/>
</body>

这会在鼠标不移动 300 毫秒后隐藏按钮,这足以让它不闪烁(每隔几毫秒隐藏和显示一次(。

如果可能的话,最好给按钮一个 id,以便清晰和易于选择。

设置按钮的 CSS to display:none;

按钮开始隐藏,在移动时,它设置为 show() ,然后如果没有检测到移动,计时器准备在 300 毫秒后再次隐藏它。如果检测到移动,则重置计时器。

var timer;
$(document ).mousemove(function(){
    $("#mouseDrivenButton" ).show();
    clearTimeout(timer);
    timer = setTimeout(function(){
        $("#mouseDrivenButton" ).hide();
    },300)
});
 #mouseDrivenButton {
   display: none;
 }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="mouseDrivenButton">Mouse Is Moving</button>

这个是纯粹的JAVASCRIPT,不需要外部脚本

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <style>
    #mouseDrivenButton {
      display: none;
    }
  </style>
  <script>
    var timer;
    document.onmousemove = function() {
      document.getElementById('mouseDrivenButton').style.display = "block";
      clearTimeout(timer);
      timer = setTimeout(function() {
        document.getElementById('mouseDrivenButton').style.display = "none";
      }, 300)
    };
  </script>
</head>
<body>
  <button id="mouseDrivenButton">Mouse Is Moving</button>
</body>
</html>