我试图在鼠标悬停时使用jQuery动画改变backgroundColor。
我检查了一些例子,我似乎有它是正确的,它与其他属性,如fontSize,但与backgroundColor我得到和“无效属性”js错误。 我正在使用的元素是div。
$(".usercontent").mouseover(function() {
$(this).animate({ backgroundColor: "olive" }, "slow");
});
什么好主意吗?
我试图在鼠标悬停时使用jQuery动画改变backgroundColor。
我检查了一些例子,我似乎有它是正确的,它与其他属性,如fontSize,但与backgroundColor我得到和“无效属性”js错误。 我正在使用的元素是div。
$(".usercontent").mouseover(function() {
$(this).animate({ backgroundColor: "olive" }, "slow");
});
什么好主意吗?
当前回答
为了达到理想的效果,我使用了CSS过渡和JQuery的组合;显然,不支持CSS过渡的浏览器不会动画,但它是一个轻量级的选项,适用于大多数浏览器,对我的要求是可接受的退化。
使用Jquery修改背景颜色:
$('.mylinkholder a').hover(
function () {
$(this).css({ backgroundColor: '#f0f0f0' });
},
function () {
$(this).css({ backgroundColor: '#fff' });
}
);
CSS使用过渡淡出背景颜色的变化
.mylinkholder a
{
transition: background-color .5s ease-in-out;
-moz-transition: background-color .5s ease-in-out;
-webkit-transition: background-color .5s ease-in-out;
-o-transition: background-color .5s ease-in-out;
}
其他回答
我也有同样的问题,并通过包含jQuery UI来修复它。以下是完整的脚本:
<!-- include Google's AJAX API loader -->
<script src="http://www.google.com/jsapi"></script>
<!-- load JQuery and UI from Google (need to use UI to animate colors) -->
<script type="text/javascript">
google.load("jqueryui", "1.5.2");
</script>
<script type="text/javascript">
$(document).ready(function() {
$('#menu ul li.item').hover(
function() {
$(this).stop().animate({backgroundColor:'#4E1402'}, 300);
}, function () {
$(this).stop().animate({backgroundColor:'#943D20'}, 100);
});
});
</script>
试试这个:
jQuery(".usercontent").hover(function() {
jQuery(this).animate({backgroundColor:"pink"}, "slow");
},function(){
jQuery(this).animate({backgroundColor:"white"}, "slow");
});
修订后的效果:
jQuery(".usercontent").hover(function() {
jQuery(this).fadeout("slow",function(){
jQuery(this).animate({"color","yellow"}, "slow");
});
});
我偶然发现这一页有同样的问题,但有以下问题:
我不能包括一个额外的jQuery插件文件与我目前的设置。 我不喜欢粘贴我没有时间阅读和验证的大块代码。 我没有css的权限。 我几乎没有时间去执行(它只是一个管理页面的视觉改进)
根据上述情况,几乎排除了所有答案。考虑到我的颜色退色非常简单,我使用了下面的快速技巧:
element
.css('color','#FF0000')
;
$('<div />')
.css('width',0)
.animate(
{'width':100},
{
duration: 3000,
step:function(now){
var v = (255 - 255/100 * now).toString(16);
v = (v.length < 2 ? '0' : '') + v.substr(0,2);
element.css('color','#'+v+'0000');
}
}
)
;
上面的代码创建了一个临时div,它永远不会放在文档流中。然后,我使用jQuery的内置动画来动画该元素的数值属性(在本例中为width),它可以表示百分比(0到100)。然后,使用阶跃函数,我用简单的十六进制计算将这个数字动画转换为文本颜色。
使用setInterval也可以实现同样的效果,但是通过使用这个方法,您可以从jQuery的动画方法(如.stop())中受益,并且您可以使用easing和duration。
显然,它只适用于简单的颜色褪色,对于更复杂的颜色转换,你需要使用上面的答案之一-或编码你自己的颜色褪色数学:)
Bitstorm拥有我见过的最好的jquery彩色动画插件。这是对jquery颜色项目的改进。它还支持rgba。
http://www.bitstorm.org/jquery/color-animation/
如果有人发现了这个。你最好使用jQuery UI版本,因为它可以在所有浏览器上运行。颜色插件在Safari和Chrome浏览器中存在问题。只是有时候有用。