简体   繁体   中英

Jquery changing background color on hover, keeps flashing

so I'm currently making a toplist and I'd like to add a little javascript to it. I've decided to make a background color fade in when a visitor hovers their mouse over a name.

But the problem is, it keeps flashing in and out, which is quite annoying! - Here is my code:

<script type="text/javascript">
    var isOn = false;
    if(isOn == false) 
    {
        $('#rank<?= $info['ID']; ?>').hover(function(){
            isOn = true;
            $('#rank<?= $info['ID']; ?>').animate({
                backgroundColor: '#FF0000'
            }); 
        });
    }
    $('#rank<?= $info['ID']; ?>').mouseout(function(){
        isOn = false;
        $('#rank<?= $info['ID']; ?>').animate({
            backgroundColor: 'white'
        });
    });

</script>

I want to fade in to a color when a visitor hovers over the area, and change back to a different color when a visitor hovers out of the area.

Thank you.

The problem is that you are using the hover shortcut incorrectly. hover actually takes two functions and binds to mouseenter and mouseleave . Your current code is binding to mouseenter and mouseout , which will cause problems.

What you actually want is this:

var isOn = false;
if(isOn == false) 
{
    $('#rank<?= $info['ID']; ?>').hover(function() {
        isOn = true;
        $('#rank<?= $info['ID']; ?>').animate({
            backgroundColor: '#FF0000'
        }); 
    },
    function() {
        isOn = false;
        $('#rank<?= $info['ID']; ?>').animate({
            backgroundColor: 'white'
        });
    });
}

You might also want to include some .stop() functions so you don't have a problem with your animation queue.

You should never use mouseover or mouseout because they fire multiple times when you enter or leave an element. See the demo at the bottom of http://api.jquery.com/mouseenter/ for an illustrative example.

You cannot animate colors using standard jQuery, you need additional scripts, EG: jQuery UI.

Also searching should have helped to fix this problem: https://stackoverflow.com/a/2302005/2373138

Use CSS(3) check here

If you want to use JS, use a mouse-enter and -leave start/stop function.

You must use the latest Jquery color plugin .

From api.jquery.com/animate/

...most properties that are non-numeric cannot be animated using basic jQuery functionality (For example, width, height, or left can be animated but background-color cannot be, unless the jQuery.Color() plugin is used).

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