Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - Using class name in CSS value

I am currently doing some styling and have thought up an interesting way to do something. I want to create a piece of text that stands out among every other bit of text on the page. Below you can see the way I've done this.

var el = document.querySelectorAll('span[class^=impact]')[0],
  col = el.className.split('-')[1];

el.style.textShadow = '2px 2px 0 #' + col;
html, body {
  width: 100%;
  height: 100%;
  margin: 0;
  background-image: url('http://i.imgur.com/UxB7TDq.jpg');
}
[class^=impact] {
  position: fixed;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  
  font-family: Impact, sans-serif;
  font-size: 72pt;
  font-weight: 800;
  text-transform: uppercase;
}
<span class="impact-008080">impact</span>
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

CSS attr

Theoretically, this type of thing is what the CSS attr property could be used for when browser support exists. Note that this won't work now, but when browser support does exist, it might look something like this:

HTML

<span class="impact" data-shadow="#008080">Impact</span>

CSS

.impact {
    /* you text and positioning styles here */

    text-shadow: 2px 2px attr(data-shadow);
}

You can read more about the attr property here: https://developer.mozilla.org/en-US/docs/Web/CSS/attr


But for now...

Your best bet is probably to continue to use JavaScript, but instead of appending the hex code to the class name, store the hex value in a data attribute of the element, allowing you to keep the class name consistent for all instances of that element.

HTML

<span class="impact" data-shadow="#fff">Impact</span>

CSS

.impact {
    /* your text and position styles here */
}

JS

var el = document.querySelector(".impact"),
    shadow = el.dataset.shadow;

el.style.textShadow = '2px 2px ' + shadow;

Here's a JSFiddle for reference: http://jsfiddle.net/galengidman/xx6r1n2o/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...