javascript - 在 mouseover() 和 mouseout() 上使用 off() 方法

标签 javascript jquery mouseover mouseout

正如我的标题所示,我在使用 JQuery 中的 off 方法与 mouseover/mouseout 相结合时遇到问题。

我的 HTML 代码(相关部分):

 <h3>Hover</h3>
 <p id="hover">Move the mouse pointer over this paragraph.</p>
 <button id="off">Press the button</button>

我的 JQuery 代码(相关部分):

$(document).ready(function(){
    $("#hover").mouseover(function(){
         $("#hover").css("background-color", "green");
   });
   $("#hover").mouseout(function(){
        $("#hover").css("background-color", "lightblue");
   });
   $("#off").click(function(){
        $("#hover").off("click");
    });
});

“悬停部分”工作正常。但是,当我按下按钮时,本应停止鼠标悬停和鼠标移出方法,但事实并非如此。

最佳答案

您应该使用 jQuery 的 unbind ,像这样启动事件处理程序:

$("#hover").unbind("mouseover mouseout");

$(document).ready(function(){
    $("#hover").mouseover(function(){
         $(this).css("background-color", "green");
   });
   $("#hover").mouseout(function(){
        $(this).css("background-color", "lightblue");
   });
   $("#off").click(function(){
        $("#hover").unbind("mouseover mouseout");
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3>Hover</h3>
 <p id="hover">Move the mouse pointer over this paragraph.</p>
 <button id="off">Press the button</button>

希望这有帮助!

关于javascript - 在 mouseover() 和 mouseout() 上使用 off() 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41244066/

相关文章:

javascript - this.controller 在 Route 类中未定义

javascript - 数据事件未触发 Node.js

javascript - 重置幻灯片以使用每个点击处理按钮从第一张幻灯片开始

php - 使用 jquery Ajax 加载内容(URL 触发)

html - 嵌入标签的鼠标离开事件

javascript - 如何同时检测按键和鼠标悬停

Javascript:Firefox 中复选框+标签+preventDefault 的问题

Javascript 手动 'declick' 然后在单击时单击子元素

javascript - 如何在动态创建的文本框中设置值

javascript - 将hoverIntent与 "mousedown"集成