【问题标题】:Dynamically changing content of a SPAN动态改变 SPAN 的内容
【发布时间】:2014-08-20 17:29:23
【问题描述】:

如何在无限循环中动态更改<span> 标签的内容。

我已尝试使用以下方法。是否可以使用纯 CSS 动画来做到这一点?如果纯 CSS 无法实现,请提出替代方法。

HTML:

<p>Lorem ipsum <span></span> sit amet.</p>

CSS:

span {
    content: '';
    animation: flip 2s infinite;
}
@keyframes flip {
    10% {
        content: 'Example no1';
    }
    40% {
        content: '';
    }
    80% {
        content: 'Example no2';
    }
    100% {
        content: '';
    }
}

Demo Fiddle

【问题讨论】:

  • 抱歉,问题不清楚。你有任何插图向我们展示你在寻找什么吗?如果您只需要在无限循环中执行 CSS3 动画,则使用 animation-iteration-count 属性和 infinite 作为值。
  • jsfiddle.net/CU2JB 之前没用过内容,告诉我它是如何工作的以及如何制作动画。
  • 你可以用this这样的JS吗?
  • 感谢您的评论,祝您有美好的一天:)。
  • 不是真的没有。我需要值作为字符串。

标签: css css-transitions css-animations css-content


【解决方案1】:

无法使用content 属性动态更改span 的内容。它最初设计为仅用于伪元素(如:before 或:after)。

但是,这可以通过 HTML 和 Javascript 来实现,如下所示:

var i = 0; // The counter variable
var arrayLength = 5; // The max length of the data array 
var dataArray = ['Example 1', 'Example 2', 'Example 3', 'Example 4', 'Example 5']; // The actual data which have to be shown in a loop

function changeval() {
    if (i == arrayLength) i = 0; // If counter reaches max length, reset it
    document.getElementById('dataSpan').innerHTML = dataArray[i]; // Set the value to the span
    i++; // Increment counter
}

setInterval(changeval, 500); // Call the function to change value at defined intervals
<!-- Just add an ID to your span to which the content must be set -->
<p>Lorem ipsum <span id='dataSpan'></span> sit amet.</p>

尽管 CSS 不是最适合您的情况,但如果不是,则可以使用一些 CSS 技巧/黑客来实现以下目标。数组中的项目数很小/有限。

body, html{
    font-size: 16px;
}
#dataSpan {
    height: 1.25em;
    overflow: hidden;
    display: inline-block;
    vertical-align: top;
    padding: 0px;
    line-height: 1.25em;
    top:0;
}
#dataSpan span {
    position: relative;
    -webkit-animation: changeContent 5s steps(4) infinite;
    -moz-animation: changeContent 5s steps(4) infinite;
    animation: changeContent 5s steps(4) infinite;
}
@-webkit-keyframes changeContent {
    from{top:0;}
    to {top:-5em;}
}
@-moz-keyframes changeContent {
    from{top:0;}
    to {top:-5em;}
}
@keyframes changeContent {
    from{top:0;}
    to {top:-5em;}
}
<p>Lorem ipsum <span id="dataSpan">
        <span>Example 1<br>Example 2<br>Example 3<br>Example 4<br>Example 5</span>
</span> sit amet.</p>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-24
    • 2017-11-17
    • 1970-01-01
    • 1970-01-01
    • 2018-10-14
    • 2013-06-14
    • 1970-01-01
    相关资源
    最近更新 更多