-
13-09-2019 - |
题
我需要与子项编号嵌套列表,如下所示:
1. Item 1
1.1 - Subitem 1
1.2 - Subitem 2
1.3 - Subitem 3
1.4 - Subitem 4
1.5 - Subitem 5
2. Item 2
2.1 - Subitem 1
2.2 - Subitem 2
2.3 - Subitem 3
2.4 - Subitem 4
2.5 - Subitem 5
好了,我知道我不能做到这一点与纯HTML。这将是巨大的,使用这样的事情,并有自动编号的子表:
<ol>
<li>
Item 1
<ol>
<li>Subitem 1</li>
<li>Subitem 2</li>
<li>Subitem 3</li>
<li>Subitem 4</li>
<li>Subitem 5</li>
</ol>
</li>
<li>
Item 2
<ol>
<li>Subitem 1</li>
<li>Subitem 2</li>
<li>Subitem 3</li>
<li>Subitem 4</li>
<li>Subitem 5</li>
</ol>
</li>
</ol>
是否有此使用JavaScript或jQuery的或东西的溶液
解决方案
如果你想用jQuery做跨浏览器:
$("ol#list ol").each(function(i, el){
$(this).children().each(function(ci,cel){
$(this).prepend('<span class="pseudo-num">' + [i + 1, ci + 1].join('.') + ' </span>');
});
}).addClass('pseudo-processed');
而在你的CSS:
ol .pseudo-num { display: none }
ol.pseudo-processed { list-style: none; padding-left: 0 }
ol.pseudo-processed .pseudo-num { display: inline; font-weight: bold }
这是只有一层。你可以修改密码创建多层次递归函数。
这是设置逐步提高你的页面。没有JavaScript它将回退到正常嵌套编号。
<强>更新强>:由于 @Gumbo 工作,我返工此代码到一个递归插件。它会使用相同的CSS正如我在前面的例子,但现在它是一个“羽翼丰满” jQuery插件与任何深度支持:
$.fn.outline = function(options, counters){
var options = $.extend({}, $.fn.outline.defaults, options),
counters = counters || [];
this.each(function(){
$(this).children('li').each(function(i){
var ct = counters.concat([i + 1]);
if(counters.length){
$('<span></span>')
.addClass(options.numberClass)
.text(ct.join('.') + ' ')
.prependTo(this);
}
$(this).children('ol').outline(options, ct);
})
});
if(!counters.length) this.addClass(options.processedClass)
}
$.fn.outline.defaults = {
numberClass: 'pseudo-num',
processedClass: 'pseudo-processed'
}
然后,您可以把它在一个特定的#id
:
$("#list").outline();
或者使用@甘博的不错选择将其应用到所有ol
标签在一个页面上:
$("ol:not(li > ol)").outline();
和您可以覆盖默认值全球范围内,或在个体基础:
$.fn.outline.defaults.processedClass = 'ol-ready';
// or
$("#list").outline({processedClass: 'ol-ready'});
其他提示
您可以使用CSS这样做的:
OL { counter-reset: item }
LI { display: block }
LI:before { content: counter(item) ". - "; counter-increment: item }
LI LI:before { content: counters(item, ".") " - "; counter-increment: item }
但是,它需要用于 counter
和counters
支持
修改强>下面是类似于dcneiner的,但有没有限制深度一个jQuery的方法:
function foo($ol, counters) {
counters = counters || [];
$ol.each(function(i) {
var $this = $(this);
$this.children("li").each(function(i) {
var $this = $(this);
$this.prepend(counters.concat([i+1]).join(".") + " ");
$this.children("ol").each(function(j) {
foo($(this), counters.concat([i+1]));
});
});
});
}
foo($("ol:not(li > ol)"));
无论JS也不jquery的但CSS:
<STYLE type="text/css">
UL, OL { counter-reset: item }
LI { display: block }
LI:before { content: counters(item, "."); counter-increment: item }
</STYLE>
不隶属于 StackOverflow