简体   繁体   English

使用setInterval的动画问题

[英]Animation issues using setInterval

I'm animating a div to left by 0px by clicking on the div colored in red. 我通过点击红色的div来动画一个div向左移动0px。 Below the div , classes are added to li's as the div moves along, but the classes gets added to only certain li's and not all. 在div下面,当div移动时,类被添加到li中,但是类只被添加到某些li而不是全部。

Is there any other logic to fix this ? 有没有其他逻辑来解决这个问题?

Fiddle - http://jsfiddle.net/AsfFQ/16/ 小提琴 - http://jsfiddle.net/AsfFQ/16/

Below is the image of the issue 以下是问题的图像 在此输入图像描述

Try this jsFiddle example . 试试这个jsFiddle示例

var pos;
var timer, selectLi = (function() {
    var $block = $('.block'),
        $container = $('.container'),
        $lis = $('.container ul li'),
        liWidth = $lis.width(),
        $selectedLi;
    return function() {
        pos = $block.offset().left - $container.offset().left;
        liNum = Math.round(pos / liWidth);
        // $selectedLi && $selectedLi.removeClass('selected');
        $selectedLi = $($lis.get(liNum));
        $('li.eligible').each(function() {
            if ($block.offset().left-3 <= $(this).offset().left) $(this).addClass('selected');
        });
    };
})();

$('.block').click(function() {
    timer = setInterval(selectLi, 30);
    $(this).animate({
        left: 0
    }, function() {
        clearInterval(timer);
    });
});

$('li').each(function() {
    $(this).addClass('eligible');
    if ($(this).offset().left > $('.block').offset().left) $(this).removeClass('eligible');
});​

This sets the eligible list items and then as the bar moves, compares their position to tjat of the bar and if they're in range, they get the class added. 这将设置符合条件的列表项,然后在条移动时,将它们的位置与条形图的tjat进行比较,如果它们在范围内,则会添加该类。

Your little animation needs only a little code. 你的小动画只需要一些代码。 See jsfiddle example 参见jsfiddle示例

var $block = $('.block'),
    start = $block.offset().left;

$block.one('click').animate({left: 0})
 .$('li').filter(function(){return $(this).offset().left<=start})
 .repeat(30).filter(function(){return $(this).offset().left>=$block.offset().left})
 .addClass('selected').unrepeat();
​

I'm using this plugin jquery-timing . 我正在使用这个插件jquery-timing


This also works when animating 100px on each click, see another fiddle : 这在每次点击动画100px时也有效,请看另一个小提琴

var $block = $('.block');
$block.on('click').animate({left: '-=100px'})
 .$('li').filter(function(){return $(this).offset().left<=$block.offset().left})
 .repeat(30).filter(function(){return $(this).offset().left>=$block.offset().left})
 .addClass('selected').unrepeat();

Have fun! 玩得开心!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM