简体   繁体   中英

Jquery animate on mouseenter

i'm not sure what is wrong with this script but it just doesn't seem to want to work. What is meant to happen is that the box should fade the color in and out according to mouseenter/leave.

$(document).ready(function() {
    $('.square-box').mouseenter(function() {
        $(this).animate({
            background-color: '#AAAAAA'
        }, 1000);
    });
    $('.square-box').mouseleave(function() {
        $(this).animate({
            background-color: '#CCCCCC'
        }, 1000);
    });
});

https://jsfiddle.net/k9met5oz/

What am i doing wrong? Thanks.

You can animate only attributes with numeric values. But you can use this plugin https://github.com/jquery/jquery-color/ for color animation. Try this:

 $(document).ready(function() { $('.square-box').mouseenter(function() { $(this).animate({ "backgroundColor": '#AAAAAA' }, 1000); }); $('.square-box').mouseleave(function() { $(this).animate({ "backgroundColor": '#CCCCCC' }, 1000); }); }); 
 .square-box { width: 200px; height: 200px; line-height: 200px; cursor: pointer; background-color: #CCC; text-align: center; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-color/2.1.2/jquery.color.js"></script> <div class="square-box">TEST BOX</div> 

Seems like you cannot animate colors by default in jquery

You can do it with changing css properties.

 $(document).ready(function() { $('.square-box').mouseenter(function() { $(this).css({ "background-color": "#aaa" }); }).mouseleave(function() { $(this).css({ 'background-color': '#CCCCCC' }) }); }); 
 .square-box { width: 200px; height: 200px; line-height: 200px; cursor: pointer; background-color: #CCC; text-align: center; transition: 1s all; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class='square-box'> TEST BOX </div> 

Jquery cannot animate colors by default. But you don't need a plugin. You can do this with CSS transitions much more easily:

 .square-box { width: 200px; height: 200px; line-height: 200px; cursor: pointer; background-color: #CCC; text-align: center; -webkit-transition:background 1s; -moz-transition:background 1s; -o-transition:background 1s; transition:background 1s } .square-box:hover {background:#AAAAAA} 
 <div class='square-box'> TEST BOX </div> 

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