根据具有data-attribute的类更改宽度/高度

时间:2013-11-22 07:34:58

标签: javascript jquery html css custom-data-attribute

我有以下JS代码,根据width HTML属性的值更改data-percentage

var addRule = (function (sheet) {
  if(!sheet) return;
  return function (selector, styles) {
    if (sheet.insertRule) return sheet.insertRule(selector + " {" + styles + "}", sheet.cssRules.length);
    if (sheet.addRule) return sheet.addRule(selector, styles);
  }
}(document.styleSheets[document.styleSheets.length - 1]));

var i = 101;
while (i--) {
  addRule("[data-percentage='" + i + "%']", "width:" + i + "%");
}

请参阅演示:http://jsfiddle.net/YYF35/

而不是width,对于某些元素,我想更改其height

如何更改代码,以便根据div的类更改元素的高度或宽度(当然,取决于data-percentage属性编号)?

我不想为它创建不同的HTML属性,如下所示:

while (i--) {
  addRule("[data-percentage-width='" + i + "%']", "width:" + i + "%");
  addRule("[data-percentage-height='" + i + "%']", "height:" + i + "%");
}

也可以使用jQuery。有什么想法吗?

2 个答案:

答案 0 :(得分:3)

您的代码正在添加规则。如果您真的想要这样做,只需添加更多规则:

var i = 101;
while (i--) {
  addRule("[data-percentage='" + i + "%'].change-width", "width:" + i + "%");
  addRule("[data-percentage='" + i + "%'].change-height", "height:" + i + "%");
}

现在,具有change-width类的元素将修改其width,具有change-height类的元素将修改其height(并且您可以同时使用两者你喜欢)。

答案 1 :(得分:0)

试试这个:

$("div[data-percentage]").each(function(){

    $(this).css({
        width: $(this).attr('data-percentage')
        //height: $(this).attr('data-percentage')
    });
});

http://jsfiddle.net/YYF35/1/