style first character of a paragraph using jquery

后端 未结 4 541
深忆病人
深忆病人 2021-01-20 12:37

i\'m looking for a way to style the first character in a paragraph. I\'ve used this function to return the first character

var x= $(\".about p:eq(0)\").text(         


        
4条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-20 13:21

    You can use CSS3 to style your first character.

    p::first-letter { 
      font-size: 200%;
      color: #8A2BE2;
    }
    

    Demo: http://jsfiddle.net/vhyqowde/

    More Info: http://www.w3schools.com/cssref/sel_firstletter.asp


    Javascript approach:

    $(document).ready(function () { 
        var elem = $("p").contents().filter(function () { return this.nodeType == 3 }).first(),
            text = elem.text().trim(),
            first = text.slice(0, 1);
    
        if (!elem.length)
            return;
    
        elem[0].nodeValue = text.slice(first.length);
        elem.before('' + first + '');
    });
    

    http://jsfiddle.net/kynt4pot/

提交回复
热议问题