问题
Okay, so this is more of a question that has lots of solutions that are not CSS, but I'm looking for doing this more from a theoretical perspective. I have an application for it, but its not worth coding it out in any other way.
The (Fun) Question
How do you color the text of an element using the text of the element? I have an element, all on it's own, which will contain a hex value for a color, and I want the text to be that color, but I want to do it only using CSS (likely only can be done using CSS 3).
Sample HTML
<div class="color_contents">#0000FF</div>
So, I've tried to use the attr()
with no success, but I'm not sure I'm using the right contents (I've tried text
, textContent
, and innerText
to no avail). Doesn't need to be cross-browser, but just a way to accomplish it.
回答1:
Currently, there is no way to use CSS to access an element's text content, not even with the CSS3 modules available today.
Regarding this:
So, I've tried to use the
attr()
with no success, but I'm not sure I'm using the right contents (I've triedtext
,textContent
, andinnerText
to no avail). Doesn't need to be cross-browser, but just a way to accomplish it.
attr()
only looks at element attributes (foo="bar"
). Since text content isn't an attribute of an HTML element (despite being a member of the corresponding DOM object), you can't query for it using that function.
There isn't a similar function for accessing an element's text content.
回答2:
You could do something like this. It's a bit hacky, but all CSS
div.color_0000FF:before{
color:#0000FF;
content: "#0000FF";
}
HTML
<div class="color_0000FF"></div>
Example: http://jsfiddle.net/s8vLy/
回答3:
The content/attr CSS properties can only be used with :before
and :after
pseudo-elements.
CSS3 will support attr
access from other properties, see https://developer.mozilla.org/en/CSS/attr.
However when/if CSS3 attr goes live, you will still not be able to acces the "contents" of a element from CSS, simply because thats not what CSS is designed for.
Bottom line, use javascript :)
来源:https://stackoverflow.com/questions/7829397/is-it-possible-via-css-3-to-set-the-color-of-text-in-an-element-using-the-text-c