来自Stackoverflow的专业人员,我有多个span元素,我需要在元素的某些顺序中添加jquery效果。我写了一个原始的方法(就像这里:JSfiddle)。
这是HTML:
<div class="content">
<span id="zoom-1" class="bold">ZOOMING 1</span>
<span id="zoom-2" class="highlight-blue">ZOOMING 2</span>
<span id="zoom-3">ZOOMING 3</span>
</div>
<div class="content">
<span id="zoom-4" class="highlight-grey">ZOOMING 4</span>
<span id="zoom-5">ZOOMING 5</span>
<span id="zoom-6" class="highlight-red bold">ZOOMING 6</span>
</div>
CSS:
.content {
position:relative;
color:#000;
line-height:50px;}
#zoom-1, #zoom-2, #zoom-3, #zoom-4, #zoom-5, #zoom-6 {
position:relative;
margin:0 auto;
font-size:0;
line-height:0;
}
.bold {font-weight:bold;}
.highlight-red {color:red;}
.highlight-blue {color:blue;}
.highlight-grey {color:grey}
.size-10 {font-size:10px;}
.size-20 {font-size:20px;}
.size-30 {font-size:30px;}
JS:
jQuery(document).ready(function(){
$('#zoom-1').animate({
'font-size':'10px'
}, 500,function(){
$('#zoom-2').animate({
'font-size':'30px'
},500,function(){
$('#zoom-3').animate({
'font-size':'20px'
},500,function(){
$('#zoom-4').animate({
'font-size':'20px'
},500,function(){
$('#zoom-5').animate({
'font-size':'10px'
},500,function(){
$('#zoom-6').animate({
'font-size':'30px'
},500);
});
});
});
});
});
});
但是如你所见,这种方式难以实现3个以上的元素。
我已经将类.bold,.highlights和.sizes定义为元素的未来属性,我尝试将.animate()与.addClass()结合使用,但没有成功。
由于我必须为每个元素“动画”超过20个具有自定义属性的元素,您能否帮助我使用先进但更容易实现的解决方案?我正在寻找兼容IE8 +的解决方案。
提前谢谢。
答案 0 :(得分:2)
遍历这些项目,阅读他们的课程并编辑他们的外观/相应地制作动画。例如,这里是您当前代码段的返工:
jQuery(document).ready(function(){
var animCounter = 0;
$("span").each(function(){
var spanClasses = $(this).attr('class');
if (spanClasses.indexOf('size-')!=-1){
var size = spanClasses.substring( spanClasses.indexOf('size-')+5 );
$(this).delay(animCounter * 500).animate({'font-size':size+'px'},500);
animCounter++;
}
});
});
此功能将遍历您的所有跨度,检查他们是否有size-...
课程。如果一个元素确实拥有它 - 它将采用之后的数字并将其用作大小参数(也不需要css类)。
请注意,每个动画都附加一个延迟计数器,以便在适当的时间为每个元素设置动画。
您可以对颜色类等执行相同的操作。此外,您可能应该使用正则表达式从类名(10
中的span-10
)重新解析属性。如果span属性之后还有其他类,则当前代码可能会中断。
更新
以下是使用正则表达式解析类属性参数的示例:
var size = spanClasses.match(/size-\d*/)[0].substring(5);
希望这有帮助!
答案 1 :(得分:1)
您可以使用延迟方法来延迟元素与先前动画所花费的时间量,尽管有许多其他属性可以为您提供排队动画的方法,但只需创建一个会增加的变量每添加一个动画,就会增加500。如下所示,你可以做同样的尝试
jQuery(document).ready(function()
{
var time=0;
$('#zoom-1').animate({'font-size':'10px'}, 500);time+=500; //or the amount
$('#zoom-2').delay(time).animate({'font-size':'30px'},500);time+=500; //or the amount
$('#zoom-3').delay(time).animate({'font-size':'20px'},500);time+=500; //or the amount
$('#zoom-4').delay(time).animate({'font-size':'20px'},500);time+=500; //or the amount
$('#zoom-5').delay(time).animate({'font-size':'10px'},500);time+=500; //or the amount
$('#zoom-6').delay(time).animate({'font-size':'30px'},500);
});