【问题标题】:accessing pseudo elements using $(this) keyword?使用 $(this) 关键字访问伪元素?
【发布时间】:2013-08-15 01:38:34
【问题描述】:
这是我的代码
var pollPercent = function() {
$("#poll li").each(function(){
var percent = $(this).attr("data-percent");
var width = (percent / 100) * 1000;
var el = $(this);
$("head").append("<style>" + el + ":before {width: " + width + "px;}</style>");
});
};
pollPercent();
那么我怎样才能指向每个 li 并更改其“伪元素之前”
【问题讨论】:
标签:
jquery
pseudo-element
【解决方案1】:
试试这个:
var text = $('#poll').find('li').map(function (i) {
var width = Math.round($(this).attr('data-percent') / 100 * 1000);
return '#poll li:nth-child(' + (i+1) + ')::before { width: ' + width + 'px; }';
}).join('');
$(document.body).append('<style>' + text + '</style>');
【解决方案2】:
您可以使用nth-child 获取单个li 元素。 each 函数有助于提供索引。
$(...).each(function(index, element) {
... "li:nth-child(" + index + "):before" ...
})