每个元素的jQuery动画

时间:2014-08-27 13:55:54

标签: javascript jquery css animation

我对Jquery的动画经验不多。我想制作一个简单的动画,逐行突出我的文字,并有可能停止。我知道如何为一行做这样的事情,但我不知道如何处理循环。 这是我的代码:

var lines = $('#page')[0].getClientRects();
for (var i=0, max = lines.length; i < max; i++)
{
    $('#under_liner')
    .queue(function() {
        $(this).css('top', lines[i].bottom).dequeue();
      })            
    .animate({
        width: lines[i].right - lines[i].left
    }, 1000 )
    .queue(function() {
    $(this).css('width', 0).dequeue();
    }); 
 }

和jsfiddle http://jsfiddle.net/mz03kfua/2

2 个答案:

答案 0 :(得分:1)

我不知道这是否正是您所寻找的,但这就是我要做的。

  1. 创建一个执行下划线的功能
  2. 对动画回调进行递归调用
  3. 创建一个全局变量以保持当前带下划线的计数
  4. 添加一个在false
  5. 时停止该功能的布尔值
    var lines = $('#page')[0].getClientRects();
    var play = true;
    var index = 0;
    
    underlineLine();
    
    $('button').click(function(){
        play = !play
        if(play){
            underlineLine()
            $(this).html("STOP")
        }else{
            $(this).html("CONTINUE")
        }
    })
    
    function underlineLine(){
        if(index >= lines.length) return
        if(play){ 
            $('#under_liner').css('top', lines[index].bottom).dequeue();   
            $('#under_liner').css('width','0px');
            $('#under_liner').animate({
                width: lines[index].right - lines[index].left
            }, 1000, function(){
                underlineLine(index++)
            })
            $('#under_liner').css('width', 0).dequeue();
        }
    }
    

    HERE IS A FIDDLE WITH THE CODE.

    希望它有所帮助。

答案 1 :(得分:1)

http://jsfiddle.net/mz03kfua/4/

var lines = $('#page')[0].getClientRects();
var current = 0;
var element;

function animateLine() {
    if(typeof lines[current] !== "object") {
        return;
    }

    var line = lines[current];
    element = jQuery("<div />", {"class": "under_liner"}).prependTo("#page");

    element.css({top: line.bottom}).animate({width: line.width}, 1000, function() {
        current++;
        animateLine();
    });


}

function stopLine(e) {
    e.preventDefault();

    element.stop(true);
}

jQuery(".stop").click(stopLine);

animateLine();
相关问题