Max*_*ahl 3 javascript css background-color switch-statement
我正在尝试根据内容交换某些特定div的背景颜色.
当他们的输入类似于"生活方式"或"政治"或"经济"或"本地"或"体育"或"新闻"时,他们的背景颜色应该互换.
var colorInput = document.getElementById('views-field-field-section').textContent;
switch (colorInput) {
case 'Lifestyle':
document.getElementById('views-field-field-section').style.backgroundColor = '#9518b8';
break;
case 'Local':
document.getElementById('views-field-field-section').style.backgroundColor = '#009fe3';
break;
case 'Sports':
document.getElementById('views-field-field-section').style.backgroundColor = '#95c11f';
break;
case 'Economy':
document.getElementById('views-field-field-section').style.backgroundColor = '#d40d10';
break;
case: 'Politics':
document.getElementById('views-field-field-section').style.backgroundColor = '#ffcc00';
break;
default:
break;
}
Run Code Online (Sandbox Code Playgroud)
您不能在html文档中多次使用ID.这将是无效的HTML.我已将id更改为类,然后使用以下代码并且它可以工作:
var colorInput = document.getElementsByClassName('views-field-field-section');
for(i=0; i<colorInput.length; i++) {
var colorInputText = colorInput[i].textContent.trim();
switch (colorInputText) {
case 'Lifestyle':
colorInput[i].style.backgroundColor = '#9518b8';
break;
case 'Local':
colorInput[i].style.backgroundColor = '#009fe3';
break;
case 'Sports':
colorInput[i].style.backgroundColor = '#95c11f';
break;
case 'Economy':
colorInput[i].style.backgroundColor = '#d40d10';
break;
case 'Politics':
colorInput[i].style.backgroundColor = '#ffcc00';
break;
default:
text ='Nix!';
}
}
Run Code Online (Sandbox Code Playgroud)
这是jsfiddle:http: //jsfiddle.net/gFN6r/505/
| 归档时间: |
|
| 查看次数: |
1876 次 |
| 最近记录: |