【问题标题】:Set background with value of data attribute使用数据属性的值设置背景
【发布时间】:2013-07-08 09:48:29
【问题描述】:

我有 16 个不同的section-tags。每个section-tag 都有一个data- 属性来为每个section 设置特定的背景颜色:

<section data-color="#A3D1B5">

现在我想将此颜色设置为背景。

我已经尝试过的方法
在这个问题CSS values using HTML5 data attribute 中说出答案,应该可以设置像background: attr(data-color); 这样的颜色,但这对我不起作用......

我查看了jQuery data(),但我不知道如何为所有section-标签设置背景。

任何其他解决方案或提示如何使用jQuery data() 处理此问题?

【问题讨论】:

  • 不是答案,所以它作为评论:attr 仅用于::before 和::after 生成的内容:stackoverflow.com/a/1044862/148412
  • 我真正想问的问题是为什么不使用类名?
  • 因为我用 ajax 加载这个部分,我更容易处理它。而且我认为当我只添加 1 条语句来设置背景时,代码行数会更少......

标签: jquery html css html5-data


【解决方案1】:

DEMO

$("section").css('background', function () { //or for code's consistency, i'd use background-color instead
    return $(this).data('color')
});

【讨论】:

  • 有趣的方法,但与each 循环相比,速度不是那么快:jsperf.com/each-vs-return1
  • @Steve 没错,我很欣赏这种评论:) 即使在你的情况下,你也应该使用对象数据而不是属性。
  • 感谢您的回答/评论。结合,最好的解决方案! +1你们俩:P
【解决方案2】:

试试这个代码,

$("section").each(function(){
    $(this).css('background',$(this).data('color'));
});

http://jsfiddle.net/ZcPYv/

【讨论】:

    【解决方案3】:

    您必须获取data-color 属性并将其分配给css 中的background:

    $('section').each(function(){
        $(this).css('background', $(this).attr('data-color'));
    });
    

    活生生的例子:http://jsfiddle.net/Pk5dK/

    【讨论】:

    • @mplungjan 两者都可以,但attr 在检索数据时似乎比data 快。
    • +1,我希望使用 this.style.backgroundColor = this.getAttribute('data-color'); 作为函数体会更快。
    【解决方案4】:

    试试这个:- http://jsfiddle.net/adiioo7/JgfkY/

    JS:-

    jQuery(function($){
        $("#section").css("background-color",$("#section").attr("data-color"));
    });
    

    HTML:-

    <section id="section" data-color="#A3D1B5">Section with custom color</section>
    

    【讨论】:

      猜你喜欢
      • 2013-08-05
      • 2012-06-22
      • 2015-08-23
      • 2010-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多