How can I read the applied CSS-counter value?

為{幸葍}努か 提交于 2019-11-27 03:29:50

问题


Say you have a CSS 2.1 counter like

ol {
  counter-reset: section;
  list-style-type: none;
}
li:before {
  counter-increment: section;
  content: counters(section, ".") " ";
}


<ol>
  <li>itemA</li>          <!-- 1     -->
  <li>itemB               <!-- 2     -->
    <ol>
      <li>itemC</li>      <!-- 2.1   -->
      <li id="foo">itemD</li>      <!-- 2.2   -->

(see https://developer.mozilla.org/en/CSS_Counters "nesting counters")

Is there a way to read/get the :before.content ("2.2" in this case) for <li id="foo"> in JavaScript?

Edit: In my case a Mozilla-only solution would suffice. But there really seems to be no way to access this information. At least I didn't find any at https://developer.mozilla.org/en/CSS_Counters ff.


回答1:


None that I can think of, no. :before pseudo-elements are not part of the DOM so there is no way to address their content.

You could make a function that scanned the stylesheet's DOM for the :before rules and worked out which rules the browser had applied where, but it would be incredibly messy.




回答2:


I thought about a workaround trying to get the .content value but even that doesn't work because its not been set. Thats really quite shocking. I don't think there actually is any easy way to get this value!

You could calculate it with some disgusting Javascript, but that would blow the whole point of this automatic css styling out the water.




回答3:


I agree with the others: there is no way of doing that currently. Therefore I suggest you replace CSS-based counters with javascript based ones. It shouldn't be too difficult to write a script in jQuery to perform the same kind of labeling of list items, and then you know what values you inserted. Perhaps you could keep the CSS-based numbering as a fallback in case javascript is disabled in the browser.




回答4:


var x = document.getElementById("foo");
var y = document.defaultView.getComputedStyle(x, "::before").getPropertyValue(
          "counter-increment");

":before" works for backward compatibility if this doesn't, I don't know current support for "::before".

Clarification: : is pseudo-class & elements in CSS2.1, :: is pseudo-element in CSS3.

You'll probably have to parse out the number with parseInt.

Unfortunately getComputedStyle is a Standards function, which means MSIE does not support this, but FF, Chrome & Safari, and Opera do.



来源:https://stackoverflow.com/questions/532073/how-can-i-read-the-applied-css-counter-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!