javascript - 脚本多次运行
问题描述
https://codepen.io/Yarwaa/pen/QBKqxK
我只是不明白为什么我的进度条会增加宽度,然后将其减小回 0,然后重新执行此操作。
为什么我的脚本多次运行以及如何停止此操作?
ps 如果我停止我的脚本,.off
它不会一次又一次地增加宽度,但是脚本只会对第一个元素起作用,它实际上只会忽略第二个元素。
我会很高兴得到任何帮助,我实际上迷失了
来自 Codepen 的代码:
<script>
$(document).ready(function(){
$(window).on('scroll', function(){
$(".progress-bar").each(function () {
var bottom_object = $(this).position().top + $(this).outerHeight();
var bottom_window = $(window).scrollTop() + $(window).height();
if( bottom_window > bottom_object ){
$(this).animate( {width: $(this).attr('aria-valuenow') + '%' }, 2000 );
}
});
});
});
</script>
<body>
<div class="block">
SCROLL DOWN
</div>
<div class="progress" id="progress">
<div class="progress-bar progress-bar-striped bg-success" id="progress-bar" role="progressbar" style="width: 0" aria-valuenow="50" aria-valuemin="0" aria-valuemax="100"></div>
</div>
<div class="block">
SCROLL DOWN
</div>
<div class="progress" id="progress">
<div class="progress-bar progress-bar-striped bg-success" role="progressbar" style="width: 0" aria-valuenow="25" aria-valuemin="0" aria-valuemax="100"></div>
</div>
</body>
解决方案
基本上发生的事情是,每次滚动到元素视图时,您都在添加另一个动画事件,这似乎导致进度条卡在一个循环中,因为它们试图相互重新调整
解决此问题的一种方法是确定动画是否已经发生。
data
使用方法的示例jQuery
$(".progress-bar").each(function(){
//Setup the data for each .progress-bar
$(this).data('scrollInitialised',false);
});
$(window).on('scroll', function(){
$(".progress-bar").each(function () {
var $this= $(this);
//Check if the progress bar animation has been initialised yet
if($this.data('scrollInitialised') === false){
var bottom_object = $this.position().top + $this.outerHeight(),
bottom_window = $(window).scrollTop() + $(window).height();
//If it has not been initialised, check if it is within view
if( bottom_window > bottom_object ){
//Progress bar is in view, now we can animate
$this.animate( {width: $this.attr('aria-valuenow') + '%' }, 2000 );
//Set scrollInitialised to true so that we do not attempt to re-animate the scrollbar again
$this.data('scrollInitialised',true);
}
}
});
});
通过检查.progress-bar
元素是否已scrollInitialised
设置,可以防止在元素上设置多个动画
推荐阅读
- python - Python 元音常量
- python-3.x - FileNotFoundError Traceback(最近一次调用最后一次)
- regex - 正则表达式匹配具有不同值的字符串
- html - div 中两个 hr 标签之间的表格。表格不会从 div 中获取所有属性
- pygame - 如何让子弹从玩家点向光标移动?
- flutter - 这是什么错误:因为 * 取决于 *
- visual-studio - 通过命令行运行但在浏览器中搜索时未找到的 Visual Studio Docker 模板容器
- c++ - 如何比较 C++ 中的长字符串?
- python - 在列表中定义的变量之后命名 Pandas 数据框
- python - 使用 Python Sound-Device 进行实时音频处理不起作用