我想循环创建一个文字旋转效果的单词数组。我的大部分都按预期工作。有什么办法可以在p元素的长度上使用css转换吗?
从具有char.length>的对象遍历时10,char.length< 5(例如)运动不顺畅,我想减轻文字在文字周围的移动,而不是突然向后跳(或向前跳,取决于单词的长度)
HTML:
<p><span id="description-rotate"></span> something built on something else.</p>
SASS:
@-webkit-keyframes rotate-text
0%
opacity: 0
30%
opacity: 1
50%
opacity: 1
70%
opacity: 1
100%
opacity: 0
p
font-family: 'Helvetica', sans-serif
.rotate-text
-webkit-animation: rotate-text 3050ms cubic-bezier(0.645, 0.045, 0.355, 1.000) infinite
-moz-animation: rotate-text 3050ms cubic-bezier(0.645, 0.045, 0.355, 1.000) infinite
-o-animation: rotate-text 3050ms cubic-bezier(0.645, 0.045, 0.355, 1.000) infinite
animation: rotate-text 3050ms cubic-bezier(0.645, 0.045, 0.355, 1.000) infinite
使用Javascript:
var descriptionArray = ['some text', 'some more text', 'some even longer text'];
var descriptionLength = descriptionArray.length;
var description = $('#description-rotate');
function loop(i) {
description.text(descriptionArray[i%descriptionLength]);
setTimeout(function() {
loop(i+1);
description.addClass('rotate-text');
}, 3050); // This duration must match the length of the animation
}
loop(0);
我意识到这可能是解释我的目标的一种不好的方式,请查看CodePen以更好地了解我正在尝试创建的内容。
谢谢!
答案 0 :(得分:5)
使用jQuery的简单示例
是将所需的循环/交换字存储到data-*
属性中:
$("[data-words]").attr("data-words", function(i, words) {
var $self = $(this).text(""),
words = words.split("|"),
tot = words.length,
c = 0;
for(var i=0; i<tot; i++) $self.append($('<span/>',{text:words[i]}));
var $words = $self.find("span");
(function loop(){
$self.animate({ width: $words.eq( c ).width() });
$words.stop().fadeOut().eq(c).fadeIn().delay(1000).show(0, loop);
c = ++c % tot;
}());
});
/* DATA-WORDS Loop/swap words in sentence */
[data-words] {
vertical-align: top;
position: static;
}
[data-words] > span {
display: none;
position: absolute;
color: #0bf;
}
<p>
This is <span data-words="some|an interesting|some longer">some</span> text
</p>
<p>
Say <span data-words="hi|wow">hi</span> to <span data-words="Javascript|Stack Overflow">mom</span>
</p>
<script src="//code.jquery.com/jquery-3.1.0.js"></script>
|
分隔的单词将转换为数组,最后转换为子<span>
元素span
元素必须绝对位于父span
答案 1 :(得分:0)
jQuery的animate()
函数怎么样?
http://api.jquery.com/animate/
您可以为数组中的每个单词触发动画。这是一个想法,你必须弄清楚如何填充变量hasMoreWordsInTheArray
和nextWordInTheArray
:
function animateParagraphTag(word) {
if(hasMoreWordsInTheArray) {
//some special code to calculate the best width based on the word's length (theNewWidthValue)
$('p').animate(
{ width: theNewWidthValue },
"fast",
animateParagraphTag(nextWordInTheArray)
);
}
}
你必须根据单词的长度来计算宽度并将其放在动画的参数内,然后,一旦p标签相应地完成扩展/收缩,它就会触发回调函数,然后你可以继续前进到数组的下一个元素(word)。