如何使用JavaScript获取此CSS元素(.questions标签:之前)?

问题描述 投票:2回答:3

在CSS文件中,我有以下代码。

.questions label:before {
content: attr(letter);
display: inline-block;
color: gray;
}

仅使用JavaScript(jQuery不是首选),我想对此CSS元素进行一些更改,例如将颜色设置为白色而不是灰色。

如果我们只处理像.questions这样的类名,我们可以做像document.getElementsByClassName("questions").style.color = "white";这样的事情但是我想用JavaScript选择整个.questions label:before

javascript jquery html css
3个回答
1
投票

您可以使用JS / jQuery操纵伪元素,而不是更改CSS,因为它们不能使用JS / jQuery操作伪元素,因为它们不是DOM的一部分,您可以在这里阅读:https://stackoverflow.com/a/21709814/8620333

document.querySelector('.questions label').classList.add('newclass');
.questions label:before {
  content: attr(letter);
  display: inline-block;
  color: gray;
}

label.newclass:before {
  color: red;
}
<div class="questions">
  <label letter="content ">text text</label>
</div>

0
投票

有很多方法可以做到这一点

var yourcss = '.questions label:before{ background-color: green }';
var yourstyle = document.createElement('style');

if (yourstyle.styleSheet) {
    yourstyle.styleSheet.cssText = yourcss;
} else {
    yourstyle.appendChild(document.createTextNode(yourcss));
}

document.getElementsByTagName('head')[0].appendChild(yourstyle);
.questions label:before {
content: attr(letter);
display: inline-block;
color: gray;
}
<div class="questions">
  <label letter="green ">Hello World!</label>
</div>

0
投票

使用computed属性获取:before值,

var color = window.getComputedStyle(
	document.querySelector('.questions label'), ':before'
).getPropertyValue('color');
console.log(color);

function changeColor(){
    var elem = document.head.appendChild(document.createElement("style"));
    var colors = ['green','blue','red'];
    elem.innerHTML = ".questions label:before {color: "+getRandom(colors)+";}";
}

function getRandom(colors){
  var random = Math.floor(Math.random() * colors.length);
  return colors[random];
}
.questions label:before {
content: attr(letter);
display: inline-block;
color: rgb(255, 0, 0);
}
<div class='questions'>
Best
<label letter='one'> Test</label>
West
</div>

<input type="button" value="Change" onclick="changeColor()">

I found this source here

© www.soinside.com 2019 - 2024. All rights reserved.