我遇到了jQuery问题,这让我的生活变得艰难。
所以,如果这JSBin
,我到目前为止所做的事情你可以看到的是,我非常接近。我需要实现的是在一个单词显示下一个单词后,在一个句子中显示单词。直到句子没有宽度为0的单词。一旦发生这种情况,该句子就会隐藏,并且下一句开始。一旦最后一句中的所有单词都可见,一切都会重新开始(无限循环)。但是,在单词之间和句子之间也存在延迟的功能。我现在不知道如何使用代码取得进展,所以我想我会问是否有人有类似的问题,或者是否有插件可以挽救我的生命。
它应该如何工作如下;
非常感谢您的任何帮助。
答案 0 :(得分:2)
以下代码应该可以解决您的问题。我添加了一些属性(数据属性),因此它更具动态性。
var sentences = $('.sentence');
var maxSentenceIndex = sentences.length - 1;
var currentSentenceIndex = 0;
var currentSentence = null;
var wordClass = '.word-row';
var standardDelay = 0;
var animationDuration = 1500;
var currentWordIndex = 0;
function loadSentence() {
currentWordIndex = 0;
currentSentence = sentences.eq(currentSentenceIndex);
if (currentSentenceIndex > maxSentenceIndex) {
currentSentenceIndex = 0;
} else {
currentSentenceIndex++;
}
currentSentence.show();
loadWord();
}
function loadWord() {
var $sentenceWords = $(currentSentence).find(wordClass);
var maxWordsIndex = $sentenceWords.length - 1;
animateWords($sentenceWords.eq(currentWordIndex));
if (currentWordIndex > maxWordsIndex) {
$sentenceWords.css('width', 0);
$(currentSentence).hide();
loadSentence();
} else {
currentWordIndex++;
}
}
function animateWords(word, callback) {
var $word = $(word);
var delay = $(word).data('delay') || standardDelay;
var width = $(word).data('width') || '100%';
var speed = $(word).data('speed') || animationDuration;
$word.animate({
width: width
}, {
duration: speed,
complete: function() {
if (typeof(callback) == 'function') {
setTimeout(callback, delay);
} else {
setTimeout(loadWord, delay);
}
}
});
}
loadSentence();
.element{
text-align: left;
color: white;
background: gray;
width: 120px;
height: 600px;
padding-top: 50pxs
}
.word-row{
overflow: hidden;
width: 0;
}
.word{
display: block;
width: 108px;
white-space: nowrap;
text-align: center;
font-size: 22px;
}
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div class="element typed-strings">
<div class="sentence sentence-1">
<div class="word-row"><span class="word">First word</span></div>
<div class="word-row"><span class="word">Second word</span></div>
<div class="word-row"><span class="word"><strong>auto</strong></span></div>
<div class="word-row"><span class="word">strong</span></div>
<div class="word-row"><span class="word">super</span></div>
<div class="word-row"><span class="word">mario</span></div>
</div>
<div class="sentence sentence-2">
<div class="word-row"><span class="word"><strong>hello</strong></span></div>
<div class="word-row"><span class="word"><strong>how is.</strong></span></div>
<div class="word-row" data-delay="1400"><span class="word"><strong>life</strong></span></div>
<div class="word-row"><span class="word"><strong>GREAT.</strong></span></div>
</div>
</div>
</body>
</html>
请告诉我这是否适合您。