最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - style first character of a paragraph using jquery - Stack Overflow

programmeradmin4浏览0评论

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();
alert(x.charAt(0));

but don't know how to style it

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();
alert(x.charAt(0));

but don't know how to style it

Share Improve this question edited Sep 16, 2014 at 15:03 Dan 9,4785 gold badges43 silver badges75 bronze badges asked Sep 16, 2014 at 14:56 PHP UserPHP User 2,4226 gold badges52 silver badges99 bronze badges 2
  • developer.mozilla/en-US/docs/Web/CSS/::first-letter – Ram Commented Sep 16, 2014 at 14:57
  • 2 Wrap a span around it. – j08691 Commented Sep 16, 2014 at 14:58
Add a ment  | 

4 Answers 4

Reset to default 8

You can use CSS3 to style your first character.

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

Demo: http://jsfiddle/vhyqowde/

More Info: http://www.w3schools./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('<span>' + first + '</span>');
});

http://jsfiddle/kynt4pot/

Use CSS first-letter selector

p::first-letter {
    color: #FF69B4;
}

This will select and style the first letter of every <p> element. JS Fiddle Demo

With Jquery : http://jsfiddle/2wkjyz4g/2/

var x= $(".about p:eq(0)").text();
var text='<span class="fChar">'+x.charAt(0)+'</span>';
$(".about p:eq(0)").html(text + x.slice(1,x.length));

With css : http://jsfiddle/pe5Loaqn/

.about p:first-child:first-letter {
    color:red;
}

because you asked for jquery solution and you selected 1st(:eq(0)) <p> tag.

update after @Garconis' ment

var parent = "p"

function styleFirst(elem){
	var content = $(elem).contents()[0];
  if(content.nodeType == 1){
  	 styleFirst(content);
  }else if(content.nodeType == 3){
     $(elem).html(style(String(content.nodeValue)));
  }
}

function style(txt){
    var newTxt = '<span class="fChar">' + txt.charAt(0) + '</span>';
		return newTxt + txt.slice(1, txt.length);
}
styleFirst(parent);
.fChar {
    color:red;
}

span{
  color: blue;
}
<script src="https://ajax.googleapis./ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<p><span><span>Win</span>ter</span> is <span>here</span> !!!!!!!!!!!</p>

Update in code:

Can retain the nodes in the para tag also can style 1st text character even if it is nested in any other element.

The code can be updated to check if 1st char is space/tab etc in style() method and subsequent styling can be applied.

After having the same initial question, I decided to take bits and pieces of other's code, and create my own solution/answer. Here is my method.

Demo: http://jsfiddle/Garconis/g72a4h03/

Reference notes in the jQuery to understand some of the reasoning.

(function($) {

  // find each instance of your target
  $('p').each(function() {

    // now check if the first character is "<" character
    // if is NOT a "<" character, then continue
    if ($(this).html()[0] != "<") {
      // good, now search the contents of the first TEXT_NODE within the selector
      var node = $(this).contents().filter(function() {
          return this.nodeType == 3
        }).first(),
        // check the start of the string (which is what the ^ is for)
        // find any white space (via the "\s")
        // and chunks of contiguous whitespace, which is what the + is for on "\s+"
        // and keep finding all instances at the start, which is what the global "/g" is for
        // and convert them into nothing
        text = node.text().replace(/^\s+/g, ''),
        // now start at the beginning (0 position) and grab the first character
        first = text.slice(0, 1);

      // if the first node isn't a TEXT_NODE, then stop here
      if (!node.length)
        return;

      // remove the text character that we grabbed
      node[0].nodeValue = text.slice(first.length);
      // now add it back, before the node we checked, with a wrapper
      node.before('<span class="fs-dropcap">' + first + '</span>');

    };

  });

})(jQuery);
span.fs-dropcap {
  color: red;
}
<script src="https://ajax.googleapis./ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<hr>
<p>&nbsp;"[yo]"This is a test <b>&nbsp; Other HTML <a href="#0;">tester</a> should not be affected by manipulations</b></p>
<hr>
<p>    This is a test <b>&nbsp; Other HTML <a href="#0;">tester</a> should not be affected by manipulations</b></p>
<hr>
<p><span>span tag here</span> This is a test <b>&nbsp; Other HTML <a href="#0;">tester</a> should not be affected by manipulations</b></p>
<hr>
<p><a href="#0">test</a> This is a test <b>Other HTML should not be affected by manipulations</b>
</p>
<hr>
<p>This is a test <b>Other HTML should not be affected by manipulations</b></p>
<hr>
<p>&nbsp; This is a test "Other HTML should not be affected by manipulations"
</p>
<hr>
<p><u>&nbsp;&nbsp;tester&nbsp;&nbsp;</u> This is a test "Other HTML should not be affected by manipulations"
</p>

发布评论

评论列表(0)

  1. 暂无评论