jQuery mouseenter() 和 mouseleave() 无法正常工作

jQuery mouseenter() and mouseleave() not working properly

本文关键字:常工作 工作 mouseleave mouseenter jQuery      更新时间:2023-09-26

我有两个简单的脚本html:

<html>
<body>
<style>
.myBtn{
    display: none
}
.myBtnReg{
    display: block
}
</style>
<button class="myBtnReg" id="btn1" >Click Me!</button>
<script src="jquery-1.11.2.min.js"></script>
<script src="js.js"></script>
</body>
</html>

和JavaScript:

$(function(){
    $("button").mouseenter(function(){
        $(this).attr("class", "myBtn");
    });
    $("button").mouseleave(function(){
        $(this).attr("class", "myBtnReg");
    });
});
我正在尝试使鼠标进入时按钮更改类并在鼠标离开时将其更改

回来的效果,上面的代码似乎无法正常工作,当我将鼠标放在按钮上时它会闪烁,所以我假设我出于某种原因不断更改类。

您可以将button放在div内,然后在将鼠标悬停在div上时切换button类(您还需要在div 上设置固定高度

$('div').hover(function() {
  $(this).find('button').toggleClass('myBtn');
});
div {
  height: 50px;
}
.myBtn {
  display: none
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <button class="myBtnReg" id="btn1">Click Me!</button>
</div>

你的风格应该是这样的

.myBtn{
    background-color:RED;
}
.myBtnReg{
    background-color:Green;
}

你的总 HTML 是这样的

<html>
<body>
<style>
  .myBtn{
        background-color:RED;
    }
    .myBtnReg{
        background-color:Green;
    }
</style>
<button class="myBtnReg" id="btn1" >Click Me!</button>
<script src="https://code.jquery.com/jquery-2.2.3.min.js" integrity="sha256-a23g1Nt4dtEYOj7bR+vTu7+T8VP13humZFBJNIYoEJo=" crossorigin="anonymous"></script>
<script src="js.js"></script>
</body>
</html>