2017-09-24 77 views
2

我不确定这个脚本有什么问题,但它似乎并不想工作。要实现的目标是,根据鼠标输入/离开,该框应该淡入淡出。在鼠标中心上的jquery动画

$(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/

我到底做错了什么? 谢谢。

+1

你最好在你的小提琴先加入jQuery的:) – bhansa

+0

哈哈是啊,我意识到,加入之后,这就是当我意识到所做的UI这行得通。 – FoxyFish

回答

4

您只能使用数值设置动画属性。但你可以使用这个插件https://github.com/jquery/jquery-color/进行彩色动画。 试试这个:

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

+1

我接受这个答案,因为它确实有效,但是我发现jquery ui有颜色动画,我只需要包含ui(或者你的例子中的这个插件)。 – FoxyFish

3

好像你不能animate colors by default in jquery

你可以改变CSS性能做到这一点。

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

+0

虽然不动画,但它只是瞬间。 – FoxyFish

+0

@FoxyFish现在检查,我在CSS中添加动画。 – bhansa

0

jQuery的不能默认动画的颜色。但是你不需要插件。你可以用CSS过渡更容易做到这一点:

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