使用jQuery为box-shadow制作动画的正确方法

时间:2010-11-09 11:56:47

标签: jquery css3 jquery-animate box-shadow

使用jQuery为 box-shadow 属性制作动画的正确语法是什么?

$().animate({?:"0 0 5px #666"});

5 个答案:

答案 0 :(得分:73)

直接回答

使用扩展.animate方法的Edwin Martin的 jQuery plugin for shadow animation ,你可以简单地使用普通语法和“boxShadow”以及颜色的每个方面 x-和y-offset blur-radius spread-radius - 获得动画效果。它包括多个影子支持。

$(element).animate({ 
  boxShadow: "0px 0px 5px 3px hsla(100, 70%, 60%, 0.8)"
}); 

改为使用CSS动画

通过更改DOM元素的style属性来实现jQuery动画,这可能会导致特殊性的惊喜并将样式信息移出样式表。

我无法找到CSS影子动画的浏览器支持统计信息,但您可以考虑使用jQuery应用基于动画的,而不是直接处理动画。例如,您可以在样式表中定义框阴影动画:

@keyframes shadowPulse {
    0% {
        box-shadow: 0px 0px 10px 0px hsla(0, 0%, 0%, 1);
    }

    100% {
        box-shadow: 0px 0px 5px 0px hsla(0, 0%, 0%, 0);
    }
}

.shadow-pulse {
    animation-name: shadowPulse;
    animation-duration: 1.5s;
    animation-iteration-count: 1;
    animation-timing-function: linear;
}

然后,您可以使用本机animationend属性将动画结束与您在JS代码中执行的操作同步:

$(element).addClass('shadow-pulse');
$(element).on('animationend', function(){    
    $(element).removeClass('shadow-pulse');
    // do something else...
});

答案 1 :(得分:30)

如果您使用的是jQuery 1.4.3+,那么您可以利用已添加的cssHooks代码。

使用boxShadow hook:https://github.com/brandonaaron/jquery-cssHooks/blob/master/boxshadow.js

您可以这样做:

$('#box').animate({
    'boxShadowX': '10px',
    'boxShadowY':'10px',
    'boxShadowBlur': '20px'
});

钩子不允许你为颜色设置动画,但我确信可以添加一些工作。

示例:http://jsfiddle.net/petersendidit/w5aAn/

答案 2 :(得分:14)

如果您不想使用插件,可以使用一些CSS来完成:

#my-div{    
  background-color: gray;
  animation: shadowThrob 0.9s infinite;
  animation-direction: alternate;
  -webkit-animation: shadowThrob 0.9s ease-out infinite;
  -webkit-animation-direction: alternate;
}
@keyframes shadowThrob {
  from {box-shadow: 0 0 30px 10px rgba(190,65,12, 0.9);}
  to {box-shadow: 0 0 30px 10px rgba(190,65,12, 0.2);}
}
@-webkit-keyframes shadowThrob {
  from {box-shadow: 0 0 30px 10px rgba(190,65,12, 0.9);}
  to {box-shadow: 0 0 30px 10px rgba(190,65,12, 0.2);}
}
/*NOTE: The animation property is not supported in Internet Explorer 9 and earlier versions.*/

检查出来:http://jsfiddle.net/Z8E5U/

如果您想要有关CSS动画的完整文档,请参阅魔法begins here..

的路径

答案 3 :(得分:3)

我喜欢ShaneSauce解决方案! 使用类而不是ID,您可以使用jQuery addClass / delay / removeClass向任何元素添加/删除效果:

$('.error').each( function(idx, el){
    $( el )
        .addClass( 'highlight' )
        .delay( 2000 )
        .removeClass( 'highlight' );
});

答案 4 :(得分:0)

以下是没有插件的情况下如何执行此操作的示例:jQuery animated Box但它没有使用插件所带来的额外功能,但我个人希望看到(并理解)疯狂背后的方法。