使用 JavaScript 检索伪元素的内容 属性 值
Retrieve a pseudo element's content property value using JavaScript
我有以下 jQuery 代码:
$.each($(".coin"), function() {
var content = "/*:before content*/";
$("input", this).val(content);
});
我想根据其伪元素的 content
属性 值 (.coin:before
) 使用 jQuery 更改每个输入元素的值。
According to MDN, the second parameter to the .getComputedStyle()
method是伪元素:
var style = window.getComputedStyle(element[, pseudoElt]);
pseudoElt (Optional) - A string specifying the pseudo-element to match. Must be omitted (or null) for regular elements.
因此您可以使用以下命令获取伪元素的 content
值:
window.getComputedStyle(this, ':before').content;
$('.coin').each(function() {
var content = window.getComputedStyle(this, ':before').content;
$("input", this).val(content);
});
如果想根据角色获取实体代码,也可以使用以下方式:
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: '[=14=]24'
}
.yen:before {
content: '[=14=]A5'
}
<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>
我有以下 jQuery 代码:
$.each($(".coin"), function() {
var content = "/*:before content*/";
$("input", this).val(content);
});
我想根据其伪元素的 content
属性 值 (.coin:before
) 使用 jQuery 更改每个输入元素的值。
According to MDN, the second parameter to the .getComputedStyle()
method是伪元素:
var style = window.getComputedStyle(element[, pseudoElt]);
pseudoElt (Optional) - A string specifying the pseudo-element to match. Must be omitted (or null) for regular elements.
因此您可以使用以下命令获取伪元素的 content
值:
window.getComputedStyle(this, ':before').content;
$('.coin').each(function() {
var content = window.getComputedStyle(this, ':before').content;
$("input", this).val(content);
});
如果想根据角色获取实体代码,也可以使用以下方式:
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: '[=14=]24'
}
.yen:before {
content: '[=14=]A5'
}
<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>