我有一个绿色的div,我想根据模型的状态值更改div的背景颜色,
<div class="panel-heading" style="background-color:#008E00">
if @Model[0].status=="Normal" - Green
if @Model[0].status=="LOW" -yellow
if @Model[0].status=="HIGH" - Red
代码
<div class="panel-heading" style="background-color:#008E00">
<h3 class="text-center">Xavier School, Nehru Rd</h3>
<hr>
DevEUI- @Model[0].deveui.ToUpper().Substring(11, 5) <span style="color:black"></span>
<hr>
<div class="row">
<div class="col-xs-4">
<img src="~/images/manhole1.png" class="img-responsive">
</div>
<div class="col-xs-4 text-right paddingtop20">
<div class="huge"><h2>@Model[0].status</h2></div>
</div>
</div>
</div>
答案 0 :(得分:0)
我认为您正在使用Vanilla Javascript。 这是一个ES5(兼容ES6)方法的示例,可让您更改div的颜色:
var Model = [{status: 'Normal'}];
function colorMyDiv(){
var color = 'black'; // default color
switch (Model[0].status) {
case 'Normal':
color = 'green';
break;
case 'LOW':
color = 'yellow';
break;
case 'HIGH':
color = 'red';
break;
}
var colorableDiv = document.getElementById('colorableDiv');
if(colorableDiv)
colorableDiv.style.backgroundColor = color;
}
function test(){
var states = ['Normal', 'LOW', 'HIGH'];
var index = 0;
var changeStateBtn = document.getElementsByTagName('button')[0];
var stateLog = document.getElementsByTagName('span')[0];
changeStateBtn.onclick = function(event){
index = (index +1)%3;
Model[0].status = states[index];
stateLog.innerHTML = states[index];
}
colorMyDiv();
setInterval( colorMyDiv, 1000);
}
test();
<button> Change state </button>
<p>state : <span>Normal</span> </p>
<div style="width: 50px; height: 50px; margin-top: 20px" id="colorableDiv"></div>
答案 1 :(得分:0)
<div class="panel-heading" style="background-color:@(Model[1].status == "LOW" ? "yellow" : "green")" >
<h3 class="text-center">main road </h3>
<hr>
DevEUI- @Model[0].deveui.ToUpper().Substring(11, 5) <span style="color:black"></span>
<hr>
<div class="row">
<div class="col-xs-4">
<img src="~/images/manhole1.png" class="img-responsive">
</div>
<div class="col-xs-4 text-right paddingtop20">
<div class="huge"><h2>@Model[0].status</h2></div>
</div>
</div>
</div>