Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

dom - Access HTML attribute value in SASS

Is it possible to access an HTML attribute value in SASS? I have a line of code that says

<ul id="my_id" data-count="3">

where the 3 is the result of some jQuery stuff. I need the 3 to calculate some CSS. How can I save it as a SASS variable?

Alternatively, is there a way of counting the number of child elements of a certain parent element? Say I have this code:

<ul id="my_id" data-count="3">
    <li>First list item</li>
    <li>Second list item</li>
    <li>Third list item</li>
</ul>

(As you might have guessed, the value of data-count matches the number of list items.) Can SASS count the list items and save that number as a variable?

Any ideas would be greatly appreciated.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Sass is just a CSS generator. It doesn't really interact with your HTML, so you can't use HTML attributes as Sass variables.

However, CSS can select based on attributes. So it will be more long-winded than you might like, but you can do something like

ul[data-count="3"]:after
  content: "There were three items in that list!"

And I think if you're willing to limit yourself only to a subset of very recent browsers?, you can use the CSS calc() function along with attr() to use the attribute in CSS-based calculations. But that's pretty bleeding edge.

? To be perfectly honest, I have no idea which versions of which browsers have fully implemented this. I'm pretty sure Firefox has it, though I've not used it, and I have no idea about other browsers. It is certainly not well-supported, at any rate.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...