我希望缩进一个数字,但是从我的 cms 生成的 html 我似乎无法连接到数字并应用样式。
<div class="content">
<b>01. Header</b>
Lorem ipsum dolor sit amet, consectetur
adipisicing elit, anim odio hic autem
delectus qui labore rerum irure autem
</div>
我想将数字包装在一个跨度中。所有的内容都是一样的。 02.[空格]标题
<div class="content">
<span="indent">01. </span><b>Header</b>
Lorem ipsum dolor sit amet, consectetur
adipisicing elit, anim odio hic autem
delectus qui labore rerum irure autem
</div>
.indent{
margin-left: -30px;
}
这是我已经开始的,但我似乎无法将它修剪到前 3 个字符,包括空格。
$('.content b').each(function() {
var tmp = [],
collecting = false;
$(this).contents().each(function() {
if (this.nodeType === Node.TEXT_NODE && $.trim(this.nodeValue).length > 0) {
if (collecting) {
tmp.push(this);
return false;
}
else {
collecting = true;
}
}
if (collecting) {
tmp.push(this);
}
});
$(tmp).wrapAll('<span class="indent" />');
});
最佳答案
为此,我建议的一种方法是:
$('.content b:first-child').replaceWith(
function(i,h){
return h.replace(/(\d+.\s)([\d\D]*)/g,'<span class="indent">$1</span><b>$2</b>');
});
如果 CSS 是一个选项:
.content {
counter-increment: headerNumber;
}
.content b:first-child::before {
content: counter(headerNumber, decimal-leading-zero);
padding-right: 2em;
color: #f90;
}
关于jquery - 从元素中获取数字并用 span 换行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12506687/