几个小时后,在几个人的帮助下,我设法用脚本解决了问题 但同样,我发现了这种风格的问题 我的问题在哪里?为什么相关文字会闪烁?
var offsetTop = $('#skills').offset().top;
function animateSkillBars() {
$( ".bar" ).each( function() {
var $bar = $( this ),
$pct = $bar.find( ".pct" ),
data = $bar.data( "bar" );
setTimeout( function() {
$bar
.css( "background-color", data.color )
.animate({
"width": $pct.html()
}, data.speed || 10, function() {
$pct.css({
"color": data.color,
"opacity": 1
});
});
}, data.delay || 0 );
});
}
;( function( $ ) {
"use strict";
$(window).scroll(function() {
var height = $(window).height();
if($(window).scrollTop()+height > offsetTop) {
animateSkillBars();
}
});
})( jQuery );
答案 0 :(得分:3)
因为你每次scrollTop
大于变量offsetTop
时都运行该函数,你可以添加一些类来检查你是否已经为条形图或包装div运行它
https://jsfiddle.net/bo3ggtx5/4/
var offsetTop = $('#skills').offset().top;
function animateSkillBars() {
$( ".bar" ).each( function() {
var $bar = $( this ),
$pct = $bar.find( ".pct" ),
data = $bar.data( "bar" );
if(!$(this).hasClass('animated')) {
setTimeout( function() {
$bar
.css( "background-color", data.color )
.animate({
"width": $pct.html()
}, data.speed || 10, function() {
$pct.css({
"color": data.color,
"opacity": 1
});
});
}, data.delay || 0 );
}
$(this).addClass('animated');
});
}
;( function( $ ) {
"use strict";
$(window).scroll(function() {
var height = $(window).height();
if($(window).scrollTop()+height > offsetTop) {
animateSkillBars();
}
});
})( jQuery );
答案 1 :(得分:0)
添加一个布尔animated
变量来检查它是否已被设置为动画,这似乎解决了闪烁文本的问题。看起来每次用户滚动时都会更新文本,这会导致文本闪烁。
HTML:
<li>
PHP
<div class="bar_container">
<span class="bar" data-bar='{ "color": "#9b59b6", "delay": 1200, "animated": false}'>
<span class="pct">60%</span>
</span>
</div>
</li>
JavaScript的:
function animateSkillBars() {
$( ".bar" ).each( function() {
var $bar = $( this ),
$pct = $bar.find( ".pct" ),
data = $bar.data( "bar" );
if (!data.animated) {
setTimeout( function() {
$bar
.css( "background-color", data.color )
.animate({"width": $pct.html()
}, data.speed || 10, function() {
$pct.css({
"color": data.color,
"opacity": 1
});
});
data.animated = true;
}, data.delay || 0 );
}
});
}
;( function( $ ) {
"use strict";
$(window).scroll(function() {
var height = $(window).height();
if($(window).scrollTop()+height > offsetTop) {
animateSkillBars();
}
});
})( jQuery );