문제

I have the following JS code that changes the width depending on value of the data-percentage HTML attribute:

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 + "%");
}

See the demo: http://jsfiddle.net/YYF35/

Instead of width, for some elements I want to change their height.

How can I change the code so that depending on class of the div I change the height or width of element (depending on the data-percentage attribute number of course)?

I don’t want to create a different HTML attribute for it, like so:

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

jQuery can be used as well. Any ideas?

도움이 되었습니까?

해결책

Your code is adding rules. If you really want to be doing that, just add more rules:

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

Now, elements with the change-width class will have their width modified, and elements with the change-height class will have their height modified (and you can use both if you like).

다른 팁

Try this:

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

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

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top