我有一个json文件,我在其中存储我的数据以生成某种图表。我希望能够根据json中的属性有条件地更改图表的颜色。当它是假的时候,颜色应该是红色,当它是真的时,它应该是绿色的。这是我的json文件:
"children": [
{
"children": [
{
"children": [],
"id": 50,
"name": "gfj",
"checked": true
}
],
"id": 51,
"name": "malek"
},
{
"children": [
{
"children": [
{
"children": [],
"id": 49,
"name": "nice",
"checked": true
}
],
"id": 48,
"name": "amira",
"checked": false
}
],
"id": 47,
"name": "mahdi"
}
],我可以将json文件中的属性"checked“到我的js文件中,但我不知道如何更改颜色,因为css文件中的颜色已更改。
_checked = function(d){ return d.checked; },这是css文件:
/*
Example fishbone styling... note that you can't actually change
line markers here, which is annoying
*/
html, body{ margin: 0; padding: 0; overflow: hidden;}
/* get it? gill? */
*{ font-family: "serif", "serif"; }
.label-0{ font-size: 2em }
.label-1{ font-size: 1.5em; fill: #06405a; }
.label-2{ font-size: 1em; fill: #06405a; }
.label-3{ font-size: .9em; fill: #888; }
.label-4{ font-size: .8em; fill: #aaa; }
.link-0{ stroke: #188fc6; stroke-width: 3px}
.link-1{ stroke: #188fc6; stroke-width: 2px}
.link-2, .link-3, .link-4{ stroke: #188fc6; stroke-width: 2px; }链接是图中的箭头,每个箭头都有自己的颜色和大小。我的问题是:如何使用在js文件中获得的"checked“属性,并在css文件中动态更改颜色。非常感谢。
发布于 2021-11-19 18:42:05
我想你不能动态地改变你的css文件。但是,您可以通过执行类似于我在下面提出的方案来获得您想要的行为。
重点是根据json中每个项目的"checked“属性动态地更改您的样式。为此,您可以使用Angular指令ngClass
CSS
istrueclass {
color:green;
}
isfalseclass {
color:red;
}
...HTML
<div *ngFor="child1 of children">
<div *ngFor="child2 of child1">
<div *ngFor="lastChild of child2">
<span [ngClass]="{
'istrueclass': lastChild.checked,
'isfalseclass': lastChild.checked,
}">
{{ lastChild.name }}
</span>
</div>
</div>发布于 2021-11-19 19:12:07
您可以根据从json文件返回的内容将类值动态设置为html元素。
例如:
Javascript文件
//grab your html element
const htmlElement = document.getElementById('id_here');
if (_checked === true) {
htmlElement.removeClass('true_case')
htmlElement.addClass('false_case')
} else {
htmlElement.removeClass('true_case')
htmlElement.addClass('false_case')
}并根据需要设置这些类的css样式。
.true_case {
color: green;
}
.false_case {
color: red;
}这个解决方案可能会显示一些错误,这个错误可以很容易地解决,但是这种方法是完全正确的,可以帮助你。
https://stackoverflow.com/questions/70038813
复制相似问题