Retrieve a pseudo element's content property value using JavaScript

懵懂的女人 提交于 2020-12-20 20:09:09

问题


I have the following jQuery code:

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

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

Here a example: http://jsfiddle.net/aledroner/s2mgd1mo/2/


回答1:


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

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

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

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

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

Updated Example

$('.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>


来源:https://stackoverflow.com/questions/34122243/retrieve-a-pseudo-elements-content-property-value-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!