在CSS值中使用类名 [英] 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>
你可以看到我基本上得到了类的第一半和应用样式,并抓住类的第二部分在JavaScript和应用阴影然后。我想做的是完全省略JavaScript并将其全部保存在CSS中。
As you can see I'm basically getting the first half of the class and applying styles to it and grabbing the second half of the class in JavaScript and applying the shadow then. What I want to do is omit the JavaScript completely and keep it all in CSS.
我没有颜色列表。显然支持任何和所有十六进制颜色。
I do not have a list of colours. Any and all hex colours are supported obviously. I would prefer to keep this format.
推荐答案
CSS attr
理论上,这种类型的东西是当浏览器支持存在时可以使用CSS attr
属性。请注意,现在不会工作,但是当浏览器支持存在时,它可能看起来像这样:
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);
}
您可以阅读更多关于 attr
属性:
https://开发人员。 mozilla.org/en-US/docs/Web/CSS/attr
You can read more about the attr
property here:
https://developer.mozilla.org/en-US/docs/Web/CSS/attr
您最好的选择是继续使用JavaScript,而不是将十六进制代码附加到类名称,而是将十六进制值存储在元素的数据属性中,允许您为该元素的所有实例保持类名称一致。
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;
这里有一个JSFiddle供参考: http://jsfiddle.net/galengidman/xx6r1n2o/
Here's a JSFiddle for reference: http://jsfiddle.net/galengidman/xx6r1n2o/
这篇关于在CSS值中使用类名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!