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);
}

增加每个li的计数器,而不是: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);    
});

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);
}

鉴于接受的答案,基本上没有CSS的净效应:

var myUnit = 100;
$('.demo').data('unit', myUnit);
$('.demo li').each(function () {
    $(this).text($('.demo').data('unit') * ($(this).index() + 1));
});
链接地址: http://www.djcxy.com/p/27490.html

上一篇: 我如何使用事件和承诺来控制程序流?

下一篇: 通过jQuery增加