获取CSS中属性的值

7lrncoxx  于 9个月前  发布在  其他
关注(0)|答案(8)|浏览(175)

我有这样的HTML代码:

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

字符串
我想在CSS中设置它的宽度等于data-width属性的值,例如:

div {
    width: [data-width];
}


我在哪里见过,但我不记得了。谢谢。

qvsjd97n

qvsjd97n1#

您需要the attr CSS function

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

字符串
问题是(截至2021年)它甚至不受一些主要浏览器(在我的情况下是Chrome)的支持:
注意事项:attr()函数可以与任何CSS属性一起使用,但对content以外的属性的支持是实验性的,对type-or-unit参数的支持是稀疏的。

l5tcr1uw

l5tcr1uw2#

如果没有伪类型的内容,你不能直接将数据属性值传递给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;
}

vmdwslir

vmdwslir3#

内联CSS variables几乎和数据属性一样具有声明性,与attr()相比,它们现在得到了广泛的支持。看看这个:

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>
ubof19bj

ubof19bj4#

另一种方法是使用CSS Custom Properties和style元素将值从HTML传递到CSS。

div {
  width: var(--width);
  height: var(--height);
  background-color: var(--backgroundColor);
}

个字符

lh80um4z

lh80um4z5#

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

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

字符串
CSS:

.foo {
    width: 70px;
}


jsFiddle

xmq68pz9

xmq68pz96#

我只是觉得这很有趣,但jQuery解决方案应该是这样的:

超文本标记语言

<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

KIND OF AN UPDATE不是你想要的,因为你想传递一个变量给width属性。在这种情况下,你也可以使用一个类。
超文本标记语言

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

CSS

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


标签:http://cdpn.io/jKDcH

irlmq6kh

irlmq6kh7#

第一个月
使用attr()获取属性的值;

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

字符串

nc1teljy

nc1teljy8#

你能试试这个吗

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

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

    });
 });

字符串

相关问题