Adding line number on <ol> <li> with alignment and width adjustment by CSS and Javascript
話說今日 (21/7/2018) 想係個logger度加 line number
個structure大約係咁:
<ol>
<li>
<pre> blah blah blah </pre>
</li>
</ol>
咁出黎就係有數字, 不過就多左粒點, 變成咁樣:
上stackoverflow d人就教用css :before selector 整個假狗counter 黎取代佢原本個數字, 出黎效果:
https://stackoverflow.com/questions/11946098/how-to-remove-dot-after-number-in-ordered-list-items-in-ol-li
出黎見到另一個問題, 就係佢每個li:before 既width都唔一樣..
result:
卡左成個鐘 食屎狗!!!!
個structure大約係咁:
<ol>
<li>
<pre> blah blah blah </pre>
</li>
</ol>
咁出黎就係有數字, 不過就多左粒點, 變成咁樣:
上stackoverflow d人就教用css :before selector 整個假狗counter 黎取代佢原本個數字, 出黎效果:
https://stackoverflow.com/questions/11946098/how-to-remove-dot-after-number-in-ordered-list-items-in-ol-li
ol {
counter-reset: item;
list-style-type: none;
padding-left: 10px
}
li {
display: -webkit-box;
}
li:before {
content: counter(item) " ";
counter-increment: item ;
color: gray;
display: block;
text-align: right;
font-size:14px;
}
(用黎收埋最尾果行用)
li:last-child:before {
content: "";
}
出黎見到另一個問題, 就係佢每個li:before 既width都唔一樣..
本來好天真地以為可以就咁計返最長數字既width, 再用jquery $("li:before").each(function(e){$(this).css('width','123');}); 類似咁一野apply落去, 點知!!!! :before係pseudo-element 所以無法直接用jquery/DOM方式去改!!!>_<
因為係set係default.css度, 所以用左個略為硬爆既做法去拎返張sheet再改佢value..
function getStyle(className) {
//[1] is default.css
var classes = document.styleSheets[1].cssRules;
for (var x = 0; x < classes.length; x++) {
if (classes[x].selectorText == className) {
return classes[x];
}
}
//有D取巧, 因為最下個粒一定係最長, 所以直接拎佢黎用hahaha
var maxWidth = window.getComputedStyle(document.querySelector('li:nth-last-child(2)'), ':before').getPropertyValue('width');
var liStyle = getStyle("li::before");
liStyle.style["width"] = maxWidth;
result:
卡左成個鐘 食屎狗!!!!



留言
張貼留言