这是我的代码:
var animationDuration = 3000;
var firstText = $(".text:first-child");
var currentText = firstText;
function changeText() {
$(currentText).css("display", "none");
var NextText = currentText.next(".text");
if (!NextText.length) NextText = firstText;
$(NextText).css("display", "block");
currentText = NextText;
}
var loopTimer = setInterval(changeText, animationDuration);
$('.animatedText').hover(function(e) {
clearInterval(loopTimer);
}, function(e) {
changeText();
loopTimer = setInterval(changeText, animationDuration);
})
.text {
display: none;
white-space: pre-wrap;
font-size: 30px;
cursor: default;
}
.text:nth-child(1) {
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section class="animatedText">
<div class="text">One</div>
<div class="text">Two</div>
<div class="text">Three</div>
<div class="text">Four</div>
</section>
目前,动画似乎在悬停时暂停,但如果您取消悬停,您会看到总是突然显示下一个 div。所以这并不是真正的“暂停”,它只是停止并显示下一个 div。持续时间会丢失。
怎么可能解决这个问题?
将非常感谢您的帮助!
最佳答案
运行函数 changeText()
时犯了一个小错误用于反向悬停。这里:
function(e) {
changeText();
loopTimer = setInterval(changeText, animationDuration);
})
因此,双 获得函数的开始。只需删除此功能运行,您将获得所需的结果。因为你已经运行了这个函数
changeText()
:loopTimer = setInterval(changeText, animationDuration);
var animationDuration = 3000;
var firstText = $(".text:first-child");
var currentText = firstText;
function changeText() {
$(currentText).css("display", "none");
var NextText = currentText.next(".text");
if (!NextText.length) NextText = firstText;
$(NextText).css("display", "block");
currentText = NextText;
}
var loopTimer = setInterval(changeText, animationDuration);
$('.animatedText').hover(function(e) {
clearInterval(loopTimer);
}, function(e) {
loopTimer = setInterval(changeText, animationDuration);
})
.text {
display: none;
white-space: pre-wrap;
font-size: 30px;
cursor: default;
}
.text:nth-child(1) {
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section class="animatedText">
<div class="text">One</div>
<div class="text">Two</div>
<div class="text">Three</div>
<div class="text">Four</div>
</section>
关于javascript - jQuery 动画应该在悬停时暂停,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66709224/