问题
After several hours and with the help of several people, I managed to solve the problem with the script.
But again, I found a problem with the style.
Where is my problem? Why does the relevant text blink?
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 );
demo: https://jsfiddle.net/bo3ggtx5/3/
回答1:
Its because you run the function everytime the scrollTop
is bigger than the variable offsetTop
you can add some class to check if you already run it for the bar or to wrapper 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 );
回答2:
Adding a boolean animated
variable to check if it's been animated once seems to fix the issue of flashing text. Looks like your text is updated every-time the user scrolls, which is causing the text to flash.
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 );
https://jsfiddle.net/bo3ggtx5/8/
来源:https://stackoverflow.com/questions/45640187/why-is-text-blinking-in-my-style