简体   繁体   中英

Set CSS counter-increment via jQuery

I want to set the CSS counter-increment attribute on " .demo:before " using jQuery.

The problem is jQuery cannot access a pseudo element. Another SO answer (which I can't seem to find now) suggested setting a data-attribute, and then using that value within the CSS, but that isn't working either. Is this something that can be accomplished?

Simplified Example: http://jsfiddle.net/4h7hk8td/

HTML:

<ul class="demo">
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
</ul>

JS:

// 1) User Sets Unit Size
var myUnit = 100;

// 2) Unit size is saved via data attribute
$('.demo li').attr('data-unit', myUnit);

CSS:

.demo {
    counter-reset: list;
}

.demo li:before {
    /* 3) CSS gets data attribute and applies as the increment. Not working :( */
    counter-increment: list attr(data-unit);
    content: counter(list);
}

You can actually use a css-preprocessor to compile the css.

I am giving an example below using scss:

It actually renders different counter increments for the passed numbers. This solution will work if you already know the values which are being used to increment. For example, if the values being passed are 100 , 200 and 300 , then you can use @each loop to compile css for those known numbers.

If you are atleast aware of range of values being passed, you can use @for loop ( use it when there are limited numbers ).

$values: 100, 200, 300;
@each $i in $values {
  .demo[data-num="#{$i}"]{
    & > li::before{
      counter-increment: list #{$i};
    }
  }
}

.demo {
    counter-reset: list;
}

.demo li:before {
    content: counter(list);
}

Working Fiddle ( change the data-num attribute value to 200 or 300 )

Here is the compiled css:

.demo[data-num="100"] > li::before {
  counter-increment: list 100;
}

.demo[data-num="200"] > li::before {
  counter-increment: list 200;
}

.demo[data-num="300"] > li::before {
  counter-increment: list 300;
}

.demo {
  counter-reset: list;
}

.demo li:before {
  content: counter(list);
}

Increment the counter for each li and not :before : http://jsfiddle.net/7vt0kf2c/ .

var myUnit = 100;
$(".demo li").css("counter-increment", "list " + myUnit);
$("button").click(function(e) {
    $(".demo li").css("counter-increment", "list " + 200);    
});

Given the accepted answer, basically the same net effect without CSS:

var myUnit = 100;
$('.demo').data('unit', myUnit);
$('.demo li').each(function () {
    $(this).text($('.demo').data('unit') * ($(this).index() + 1));
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM