Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
175 views
in Technique[技术] by (71.8m points)

css - Dynamically changing content of a SPAN

How can I dynamically change the content of a <span> tag in an infinite loop.

I have tried using the below method. Is it possible to do this with pure CSS animations? If it is not possible with pure CSS, please suggest an alternate method.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Changing the content of a span dynamically using the content property is not possible. It was originally designed to be used only with pseudo-elements (like :before or :after).

However, this can be achieved with just HTML and Javascript like shown below:

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...