正如我的标题所示,我在使用 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/