Javascript 如何使用jQuery设置Twitter引导进度条的动画

Javascript 如何使用jQuery设置Twitter引导进度条的动画,javascript,jquery,twitter-bootstrap,Javascript,Jquery,Twitter Bootstrap,我试图用jQuery制作动画。但当我前后滚动时,它会保持动画效果,我希望宽度为width:50%,但它会不断增加宽度 JS小提琴: var target=$('.target').offset().top+1; $(文档)。滚动(函数(){ if($(this).scrollTop()>目标){ $('.progress bar')。设置动画({ “宽度”:“50%” }); } }); 。进度{ 边缘顶部:600px; } .目标{ 高度:1000px; } 完成60% 当您设置从下到上滚

我试图用jQuery制作动画。但当我前后滚动时,它会保持动画效果,我希望宽度为
width:50%
,但它会不断增加宽度

JS小提琴:

var target=$('.target').offset().top+1;
$(文档)。滚动(函数(){
if($(this).scrollTop()>目标){
$('.progress bar')。设置动画({
“宽度”:“50%”
});
}
});
。进度{
边缘顶部:600px;
}
.目标{
高度:1000px;
}

完成60%

当您设置从下到上滚动时启动动画时,为什么希望该值大于目标偏移值

progress{
   margin-top:200px;
}

$(document).scroll(function(){
    if( $(this).scrollTop() > 0 ){
    $('.progress-bar').css({
        width:'50%'
    });
  }
  else{
    $('.progress-bar').css({
        width:'0%'
    });
  }
});

为什么要将其设置为大于目标偏移值,当您从下向上滚动时,它将启动动画

progress{
   margin-top:200px;
}

$(document).scroll(function(){
    if( $(this).scrollTop() > 0 ){
    $('.progress-bar').css({
        width:'50%'
    });
  }
  else{
    $('.progress-bar').css({
        width:'0%'
    });
  }
});
请试试这个:

var target = $('.target').offset().top + 1;

var animateProgressBar = (function() {
    var animated = false;
    return function () {
        if (!animated) {
            animated = true;
           $('.progress-bar').animate({
             'width':'50%'
           });
        }
    };
})();

$(document).scroll(function(){
    if( $(this).scrollTop() > target ){
        animateProgressBar();
    }
});
演示:

请尝试以下操作:

var target = $('.target').offset().top + 1;

var animateProgressBar = (function() {
    var animated = false;
    return function () {
        if (!animated) {
            animated = true;
           $('.progress-bar').animate({
             'width':'50%'
           });
        }
    };
})();

$(document).scroll(function(){
    if( $(this).scrollTop() > target ){
        animateProgressBar();
    }
});

演示:

Bootstrap3进度条组件已附带动画。更改宽度时,只需将
animate()
更改为
css()

$('.progress-bar').css({
  'width': '50%'
});
var target=$('.target').offset().top+1;
$(文档)。滚动(函数(){
if($(this).scrollTop()>目标){
$('.progress bar').css({
“宽度”:“50%”
});
}
});
。进度{
边缘顶部:600px;
}
.目标{
高度:1000px;
}

完成60%

Bootstrap3进度条组件已经附带动画。更改宽度时,只需将
animate()
更改为
css()

$('.progress-bar').css({
  'width': '50%'
});
var target=$('.target').offset().top+1;
$(文档)。滚动(函数(){
if($(this).scrollTop()>目标){
$('.progress bar').css({
“宽度”:“50%”
});
}
});
。进度{
边缘顶部:600px;
}
.目标{
高度:1000px;
}

完成60%

但如果您向上滚动,它会再次设置动画。我想它是动画一次,当网页loads@Daniel好的,然后删除else语句,当您从顶部滚动时,它会工作一次。但如果您向上滚动,它会再次设置动画。我想它是动画一次,当网页loads@Daniel好的,然后删除else语句,当您从顶部滚动时,它只工作一次。