Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...