基本上,我试图用span标记包装段落的第一个文本字符。这个span标签允许我将第一个文本字符设置为dropcap。
我对:first-letter
的CSS不感兴趣,因为它有各种限制,特别是当第一个字符ISN是一个字母时。
此方法非常接近,但问题是:
如果第一个元素是span
标记,它会找到该标记后的第一个文本节点...所以它定位错误的字符:
http://jsfiddle.net/Garconis/3kkvszLt/4/
注意:
基本上我以前发现的所有jQuery解决方案仅限于查找某些字符......或者它们在段落中删除HTML元素......或者如果HTML元素是第一件事,它们会破坏HTML标记在该段内。
这个并不涵盖所有角色。基本上,我希望它适用于任何角色,除非它是一个HTML元素......我认为可以通过确保它不会定位<
字符来完成。
http://jsfiddle.net/Garconis/026xwx4u/
这似乎有效,但由于某种原因删除了第一个HTML元素之前的空格:http://jsfiddle.net/Garconis/3kkvszLt/
答案 0 :(得分:0)
这似乎有效,除非任何人都能找到它的错误:http://jsfiddle.net/Garconis/g72a4h03/
(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.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<hr>
<p> "[yo]"This is a test <b> Other HTML <a href="#0;">tester</a> should not be affected by manipulations</b></p>
<hr>
<p> This is a test <b> 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> 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> This is a test "Other HTML should not be affected by manipulations"
</p>
<hr>
<p><u> tester </u> This is a test "Other HTML should not be affected by manipulations"
</p>