简体   繁体   中英

jQuery mouseenter() and mouseleave() not working properly

I have two simple script 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>

and javascript:

$(function(){
    $("button").mouseenter(function(){
        $(this).attr("class", "myBtn");
    });
    $("button").mouseleave(function(){
        $(this).attr("class", "myBtnReg");
    });
});

I'm trying to make an effect where the button changes class when ever the mouse enters and change it back when the mouse leaves, the code above doesn't seem to work properly, when I put my mouse over the button it flickers, so I assume I changes class constantly for some reason.

You can put button inside div and then toggleClass of button when you hover over div (you also need to set fixed height on 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> 

your style should be like

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

your total html is like this

<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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM