我使用HTML / CSS / JS创建了一个文本自动收录器,但几分钟后文本更改与动画失去同步,文本在可见时开始变化。如何改进代码,使其仅在隐藏时才会发生变化?
var arr = ["text1", "text2", "text3", "text4"];
(function headerMessage(counter) {
var text = arr[counter];
$('.header-message > span').text(text).animate({
'margin-left': '0px'
}, 500).delay("3000").animate({
'margin-left': '-300px'
}, 500);
delete arr[counter];
arr.push(text);
setTimeout(function() {
headerMessage(counter + 1);
}, 4000);
})(0);
.header-message {
border-left: 1px solid #e3e3e3;
padding-left: 10px;
line-height: 58px;
vertical-align: middle;
float: left;
margin-left: 10px;
overflow: hidden;
}
.header-message span {
font-family: Raleway;
font-size: 14px;
color: #979797;
font-weight: 500;
height: 30px;
line-height: 30px;
margin-left: -300px;
vertical-align: middle
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="header-message">
<span style="margin-left: 0px;">We love to help businesses like yours.</span>
</div>
Jsfiddle https://jsfiddle.net/qhtbsh2L/
答案 0 :(得分:0)
您不应该使用单独的setInterval。尝试将更改文本操作排队到动画链中。
var arr = ["text1", "text2", "text3", "text4"];
(function headerMessage(counter) {
var text = arr[counter];
$('.header-message > span').text(text).animate({
'margin-left': '0px'
}, 500).delay("3000").animate({
'margin-left': '-300px'
}, 500).queue(function(next) {
headerMessage(counter + 1);
next();
});
delete arr[counter];
arr.push(text);
})(0);
.header-message {
border-left: 1px solid #e3e3e3;
padding-left: 10px;
line-height: 58px;
vertical-align: middle;
float: left;
margin-left: 10px;
overflow: hidden;
}
.header-message span {
font-family: Raleway;
font-size: 14px;
color: #979797;
font-weight: 500;
height: 30px;
line-height: 30px;
margin-left: -300px;
vertical-align: middle
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="header-message">
<span style="margin-left: 0px;">We love to help businesses like yours.</span>
</div>