获取CSS中的属性值

时间:2013-08-18 15:15:00

标签: html css css3

我有这个HTML代码:

<div data-width="70"></div>

我想将CSS中的宽度设置为等于data-width属性的值,例如像这样的东西:

div {
    width: [data-width];
}

我看到这是在某个地方完成的,但我记不住了。感谢。

8 个答案:

答案 0 :(得分:36)

这就是我想要的:

https://developer.mozilla.org/en-US/docs/Web/CSS/attr

问题在于,即使是某些主流浏览器也不支持它,在本例中为Chrome。

答案 1 :(得分:11)

您无法直接将数据属性值传递给没有伪类型内容的css。 相反,你可以这样做.. CHECK THIS FIDDLE

<div data-width="a"></div><br>
<div data-width="b"></div><br>
<div data-width="c"></div>

CSS

div[data-width="a"] {
    background-color: gray;
    height: 10px;
    width:70px;
}
div[data-width="b"] {
    background-color: gray;
    height: 10px;
    width:80px;
}
div[data-width="c"] {
    background-color: gray;
    height: 10px;
    width:90px;
}

答案 2 :(得分:3)

CSS是关于特定html元素的静态样式信息,而不是相反的方式。如果你想使用CSS来设置div的宽度,我建议你使用类:

HTML:

<div class="foo"></div>

CSS:

.foo {
    width: 70px;
}

jsFiddle

答案 3 :(得分:2)

内联CSS variables几乎与数据属性一样声明性,与attr()相比,它们现在是widely supported。检查一下:

var elem = document.getElementById("demo");
var jsVar = elem.style.getPropertyValue("--my-var");
function next() {
  jsVar = jsVar % 5 + 1; // loop 1..5
  elem.style.setProperty("--my-var", jsVar);
}
.d1 {
  width: calc( var(--my-var) * 100px );
  background-color: orange;
}
.d2 {
  column-count: var(--my-var);
}
<button onclick="next()">Increase var</button>
<div id="demo" style="--my-var: 2">
  <div class="d1">CustomWidth</div>
  <div class="d2">custom columns number custom columns number custom columns number custom columns number custom columns number custom columns number custom columns number</div>
</div>

答案 4 :(得分:1)

我只是玩得很​​开心,但jQuery解决方案会是这样的:

<强> HTML

<div class='foo' data-width='70'></div>
<div class='foo' data-width='110'></div>
<div class='foo' data-width='300'></div>
<div class='foo' data-width='200'></div>

<强> CSS

.foo {
  background: red;
  height: 20px;
  margin-bottom: 10px;
  width: 0; /** defaults to zero **/
}

<强>的jQuery

$(document).ready(function(){
  $('.foo').each(function(i) {
    var width = $(this).data('width');
    $(this).width(width);
  });
});

Codepen草图:http://cdpn.io/otdqB


最新消息 不是你想要的,因为你想将一个变量传递给width属性。在这种情况下你也可以使用一个类。

<强> HTML

<div data-width='70'>Blue</div>

<强> CSS

div[data-width='70'] {
  width: 70px;
}

草图:http://cdpn.io/jKDcH

答案 5 :(得分:0)

你可以试试吗

 $(funcation(){
    $( "div" ).data( "data-width" ).each(function(this) {

        $(this).width($(this..data( "data-width" )))

    });
 });

答案 6 :(得分:0)

另一种方法是将CSS Custom Properties与样式元素一起使用,以将值从HTML传递到CSS。

div {
  width: var(--width);
  height: var(--height);
  background-color: var(--backgroundColor);
}
<div
  style="
    --width: 50px;
    --height: 25px;
    --backgroundColor: #ccc;
  "
></div>

<div
  style="
    --width: 100px;
    --height: 50px;
    --backgroundColor: #aaa;
  "
></div>

答案 7 :(得分:-1)

<div data-width="70"></div>

使用`attr()`获取属性值;

div {
    width: attr(data-width);
}