首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >当使用变量引用数组的索引时,无法更改Jquery中的css

当使用变量引用数组的索引时,无法更改Jquery中的css
EN

Stack Overflow用户
提问于 2013-03-04 17:11:39
回答 1查看 190关注 0票数 1
代码语言:javascript
复制
var bubble = [$('#bubble1'), $('#bubble2'), $('#bubble3'), $('#bubble4'), $('#bubble5'), $('#bubble6')];
var bubbleFirst = 0;
var visibleBubbles = 3;
var bubbleHeight = 200;
var bubbleTimeDelay = 5000;

var bubbleTimer = setTimeout(function(){animateBubbles();}, bubbleTimeDelay/2);

function animateBubbles(){
    clearTimeout(bubbleTimer);//stop from looping before this is finished

    for(var i = 0; i < visibleBubbles + 1; i++){
        count = i + bubbleFirst;
        if ( count >= bubble.length ) count = count - bubble.length;//keep index inside array
        bubble[count].animate({top:'-=' + bubbleHeight}, 2000);
    }
    bubble[bubbleFirst].css('top', '600px');//put elements moving off top to bottom
    //resetBubbles();
    bubbleFirst++;
    if(bubbleFirst >= bubble.length) bubbleFirst = 0;//bubbles have looped
    bubbleTimer = setTimeout(function(){animateBubbles();}, bubbleTimeDelay);//start looping again
}
  • bubble1从top: 0px;开始
  • bubble2从top: 200px;开始
  • bubble3从top: 400px;开始
  • 冒泡4-6从top: 600px;开始
  • 它们都是包装器div中的position: absolute

为代码转储表示歉意。我的问题都集中在第16行:

代码语言:javascript
复制
bubble[bubbleFirst].css('top', '600px');

这段代码似乎从未执行过,我的控制台中没有错误,我已经验证了bubblebubbleFirst正在使用console.log返回正确的元素。(这是一个div)

我目前正在使用解决办法,但它不是动态的:

代码语言:javascript
复制
function resetBubbles(){
    /*bubble[bubbleFirst].css('top', '600px');//put elements moving off top to bottom*/
    if(bubble[0].css('top') == '-200px') bubble[0].css('top', '600px');
    if(bubble[1].css('top') == '-200px') bubble[1].css('top', '600px');
    if(bubble[2].css('top') == '-200px') bubble[2].css('top', '600px');
    if(bubble[3].css('top') == '-200px') bubble[3].css('top', '600px');
    if(bubble[4].css('top') == '-200px') bubble[4].css('top', '600px');
    if(bubble[5].css('top') == '-200px') bubble[5].css('top', '600px');
}

我不知道为什么这不起作用,这可能是我的逻辑错误。但我无法为我的一生找到它。任何帮助都将不胜感激。耽误您时间,实在对不起。

EN

回答 1

Stack Overflow用户

发布于 2013-03-04 17:19:12

对动画的调用是否可能与您的自定义设置(顶层属性)发生冲突?即。您可以设置它,但是top立即又被animate修改了。您可以向animate传递一个回调,该回调将在动画完成后运行。这时你应该重新设置你的气泡位置。

代码语言:javascript
复制
function animate_bubble(index) {
    bubble[index].animate({ top: "0px" }, 2000 /* 2 seconds */, function () {
        bubble[index].css({ top: "600px" });
        animate_bubble(index);
    }
}
animate_bubble(0);
animate_bubble(1);
// etc .. probably do this in a for-loop

你需要找到一些方法来取消动画,虽然,应该不会太难。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15207082

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档