2

Hello is there any way i can make 2nd word in different color with in a line by using css?

for ex:

<h2>Change color by css</h2>

here i want to change "color" will be different color.

4

3 回答 3

5

For this to work (there is no :secondWord pseudo-selector, sadly) you have to use JavaScript, so I'll offer a relatively simple suggestion that allows you to define a class-name to use as a style-hook:

Object.prototype.styleSecondWord = function(styleHook){
    styleHook = styleHook || 'secondWord';
    var text = '',
        words = [];
    for (var i = 0, len = this.length; i<len; i++){
        words = (this[i].textContent || this[i].innerText).split(/\s+/);
        if (words[1]) {
            words[1] = '<span class="' + styleHook + '">' + words[1] + '</span>';
            this[i].innerHTML = words.join(' ');
        }
    }
};

document.getElementsByTagName('h2').styleSecondWord('classNameToUse');

JS Fiddle demo.

The above function updated in order to allow a specific element-type to be supplied (though it'll default to a span if none is provided):

Object.prototype.styleSecondWord = function (styleHook, styleElem) {
    styleHook = styleHook || 'secondWord';
    styleElem = styleElem || 'span';
    var open = '<' + styleElem + ' class="' + styleHook + '">',
        close = '</' + styleElem + '>',
        text = '',
        words = [];
    for (var i = 0, len = this.length; i < len; i++) {
        words = (this[i].textContent || this[i].innerText).split(/\s+/);
        if (words[1]) {
            words[1] = open + words[1] + close;
            this[i].innerHTML = words.join(' ');
        }
    }
};

document.getElementsByTagName('h2').styleSecondWord('classNameToUse', 'em');

JS Fiddle demo.

于 2013-03-30T20:41:29.630 回答
4

In the HTML

<h2>Change <span class ="color">color</span> by css</h2>

then the CSS in the stylesheet

.color {color: blue;}

replace blue with the colour you want

于 2013-03-30T20:31:13.463 回答
0

You've to style an element in order to achieve that, so you'd have to add a span and style it. Or maybe an em or strong if this particular word is used with some degree of emphasis.

Fiddle: http://jsfiddle.net/zrsaW/

I styled all span in an h2 element but in real world, you'll usually add a class to this span and use this class as a selector to your styling instructions ;)

于 2013-03-30T20:24:14.937 回答