使用JavaScript检索伪元素的content属性值

使用JavaScript检索伪元素的content属性值

问题描述:

我有以下jQuery代码:

I have the following jQuery code:

$.each($(".coin"), function() {
    var content = "/*:before content*/";
    $("input", this).val(content);
});

我想根据其伪元素的 content 属性值( .coin:before )使用jQuery更改每个输入元素的值.

I'd like to change the value of each input element using jQuery based on its pseudo element's content property value (.coin:before).

这里是一个示例: http://jsfiddle.net/aledroner/s2mgd1mo/2/

.getComputedStyle()方法是伪元素:

According to MDN, the second parameter to the .getComputedStyle() method is the pseudo element:

var style = window.getComputedStyle(element[, pseudoElt]);

pseudoElt(可选)-一个字符串,指定要匹配的伪元素.对于常规元素,必须省略(或为null).

pseudoElt (Optional) - A string specifying the pseudo-element to match. Must be omitted (or null) for regular elements.

因此,您可以使用以下命令来获取伪元素的 content 值:

Therefore you could use the following in order to get the pseudo element's content value:

window.getComputedStyle(this, ':before').content;

更新示例

$('.coin').each(function() {
  var content = window.getComputedStyle(this, ':before').content;
  $("input", this).val(content);
});

如果要基于字符获取实体代码,还可以使用以下代码:

If you want to get the entity code based on the character, you can also use the following:

function getEntityFromCharacter(character) {
  var hexCode = character.replace(/['"]/g, '').charCodeAt(0).toString(16).toUpperCase();
  while (hexCode.length < 4) {
    hexCode = '0' + hexCode;
  }

  return '\\' + hexCode + ';';
}
$('.coin').each(function() {
  var content = window.getComputedStyle(this, ':before').content;
  $('input', this).val(getEntityFromCharacter(content));
});

.dollar:before {
  content: '\0024'
}
.yen:before {
  content: '\00A5'
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="coin dollar">
  <input type="text" />
</div>
<div class="coin yen">
  <input type="text" />
</div>