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
396 views
in Technique[技术] by (71.8m points)

javascript - Style the nth letter in a span using CSS

I have:

<span id="string">12h12m12s</span>

and I'm looking to make the h, m and s smaller than the rest of the text. I've heard of the nth-letter pseudo element in css, but it doesn't seem to be working:

#string:nth-letter(3),
#string:nth-letter(6),
#string:nth-letter(9) {
    font-size: 2em;
}

I know I could use javascript to parse the string and replace the letter with surrounding span tags and style the tags. However, the string is updated every second and it seems parsing that often would be ressource intensive.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Performance-wise, I'd recommend a span hell.

<span id="string"><span id="h">12</span><span class="h">h</span><span id="m">12</span><span class="m">m</span><span id="s">12</span><span class="s">s</span></span>

One span for each h, m and s letters so you can style them properly (can apply either the same or different styling for each).

And another span for each number so you can cache the references. In sum, here's a JS for a very simplistic local-time clock:

//cache number container element references
var h = document.getElementById('h'),
    m = document.getElementById('m'),
    s = document.getElementById('s'),
    //IE feature detection
    textProp = h.textContent !== undefined ? 'textContent' : 'innerText';

function tick() {
    var date = new Date(),
        hours = date.getHours(),
        mins = date.getMinutes(),
        secs = date.getSeconds();
    h[textProp] = hours < 10 ? '0'+hours : hours;
    m[textProp] = mins < 10 ? '0'+mins : mins;
    s[textProp] = secs < 10 ? '0'+secs : secs;
}
tick();
setInterval(tick, 1000);

Fiddle

This illustrates the basic idea of cached selectors. By not re-creating the elements, you also have a good performance boost.

Though, once a second isn't very heavy work for something so simple (unless you have hundreds of clocks in your page).


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

...