当鼠标(指点设备)未激活(不移动)时隐藏按钮

时间:2016-02-14 03:55:31

标签: javascript html events button hide

我试图在鼠标不移动时隐藏按钮。这就是全部。我在这里找到了一个解决方案,但它引用了一个谷歌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>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:0)

这样在鼠标移动300ms后隐藏按钮,这足以让它不闪动(隐藏并显示每隔几毫秒)。

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

设置按钮to display:none;

的CSS

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

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


<button id="mouseDrivenButton">Mouse Is Moving</button>
&#13;
&#13;
&#13;

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

&#13;
&#13;
<!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>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

我相信你找到的解决方案有一个你不想要的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>

相关问题