简体   繁体   English

使用 Javascript 使“无序列表”表现得像“有序列表”

[英]Make "Un-ordered list" behave like an "ordered list" with Javascript

I need to display numbers which each list item in an un-ordered list.我需要显示无序列表中每个列表项的数字。 To achieve this, I tried to convert an un-ordered ul list tag into an ordered ol list tag (see my script below).为此,我尝试将未排序的ul列表标记转换为有序的ol列表标记(请参阅下面的脚本)。 I need to do this because I want each li tag to display its order number next to it.我需要这样做是因为我希望每个li标签都在它旁边显示其订单号。

Here is the script that I tried which I found on codepen :这是我在 codepen 上找到的我尝试过的脚本:

var ul = document.getElementsByClassName("productGrid")[0]
var ol = document.createElement("ol");

var li = ul.querySelectorAll('li');
for(var i=0;i<li.length;i++) {
  ol.appendChild(li[i]);
}

setTimeout(function() {
  ul.parentNode.replaceChild(ol,ul);
},1000);

This works but as expected it ruined the "styles" set to that ul tag.这有效,但正如预期的那样,它破坏了设置为该ul标签的“样式”。 So instead of turning it into an actual ol tag, I need to keep it as a ul and display numbers some other way.因此,与其将其转换为实际的ol标签,不如将其保留为ul并以其他方式显示数字。

How can I use JavaScript to find out how many li 's are inside the ul tag and then display the appropriate number within the li tag (via something like a span tag)如何使用 JavaScript 找出ul标签内有多少li ,然后在li标签内显示适当的数字(通过类似span标签的东西)

Any help with this would be much appreciated.对此的任何帮助将不胜感激。

Have you considered a pure-CSS based approach instead?您是否考虑过基于纯 CSS 的方法?

You could achieve a similar counting effect on an unordered-list without the need for JavaScript via the :before pseudo-element, and the counter-reset and counter-increment CSS properties.您可以通过:before伪元素以及counter-resetcounter-increment CSS 属性在无序列表上实现类似的计数效果,而无需 JavaScript。

Here's a snippet to demonstrate this technique in action:以下是演示此技术实际应用的片段:

 .number-list { /* Init your custom counter for children */ counter-reset: number-list-counter; /* Hide point list style */ list-style:none; } .number-list li { position:relative; } .number-list li:before { /* Set content of pseduo element by parent counter and increment the counter */ content: counter(number-list-counter); counter-increment: number-list-counter; /* Offset position of counter pseduo elements */ position:absolute; top:0; left:-2rem; /* Apply some styling to the numbering */ color: red; font-weight:bold; font-size:1.5rem; }
 <ul class="number-list"> <li>Apple</li> <li>Orange</li> <li>Banana</li> <ul>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM