【问题标题】:Use off()-method on mouseover() and mouseout()在 mouseover() 和 mouseout() 上使用 off() 方法
【发布时间】:2016-12-20 13:57:55
【问题描述】:

正如我的标题所示,我在将 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");
    });
});

“悬停部分”工作正常。但是当我按下应该停止鼠标悬停和鼠标悬停方法停止的按钮时,它没有。

【问题讨论】:

    标签: javascript jquery mouseover mouseout


    【解决方案1】:

    你应该使用 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>

    希望这会有所帮助!

    【讨论】:

    • @Waltswen - 如果您认为此答案正确且有帮助,请接受并点赞此答案,因为它激励我回答此类其他问题并帮助其他人快速找到正确答案!
    【解决方案2】:

    该元素没有添加click 事件侦听器,而是添加了mouseovermouseout。因此,没有off() 无效。使用:

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

    $(document).ready(function(){
        $("#hover").mouseover(function(){
             $("#hover").css("background-color", "green");
       });
       $("#hover").mouseout(function(){
            $("#hover").css("background-color", "lightblue");
       });
       $("#off").click(function(){
            $("#hover").off("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>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-11
      • 1970-01-01
      • 1970-01-01
      • 2011-03-03
      • 1970-01-01
      • 2012-04-24
      相关资源
      最近更新 更多