最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Changing color using variable - Stack Overflow

programmeradmin2浏览0评论

I just need to change color from the array

var colorr = ["#008000", "#e0ffc1", "#ffc1e1", "#cc0000"];  
<span class='badge' style='background-color: colorr[0]; font-size: 25px ;'>

How can i do this?

I just need to change color from the array

var colorr = ["#008000", "#e0ffc1", "#ffc1e1", "#cc0000"];  
<span class='badge' style='background-color: colorr[0]; font-size: 25px ;'>

How can i do this?

Share Improve this question asked Apr 8, 2014 at 7:06 VikneshwarenVikneshwaren 332 silver badges12 bronze badges 1
  • 6 Since you've hardcoded the colors in your JS file, why not hardcode them in a CSS file add use classes? – CodingIntrigue Commented Apr 8, 2014 at 7:09
Add a ment  | 

8 Answers 8

Reset to default 6

Use jQuery (of course ;))

$(".badge").css('background-color', colorr[0]);

You will need to find a way to select you element. This example uses the class selector. You could also give it an id, and use $("#theid") instead.

Or use any other selector mechanism provided by jQuery, see: http://api.jquery./category/selectors/

simply by this :

 $(".badge").css({backgroundColor: colorr[0]});

Live example here

With JS

document.getelementsbyclassname('badge')[0].style.backgroundColor = colorr[0];

If you need to keep changing the colours from the array, you can do:

var elements = document.getElementsByClassName('badge');
var colorr = ["#008000", "#e0ffc1", "#ffc1e1", "#cc0000"];
var index = 0;
setInterval(function () {
    index = (index + 1) % (colorr.length);
    for (var i = 0; i < elements.length; i++) {
        elements[i].style.backgroundColor = colorr[index];
    }
}, 5000);

Try this

Use

$(".badge:eq(3)").css('background-color', colorr[0]); 

Or

$("span.badge:eq(3)").css('background-color', colorr[0]); 

It will apply color to fourth span has class .badge

See the demo

$.each(colorr , function(i, item) { 
    $(".badge").css('background-color', item); 
});

Try the following

Use a function in script tag

function load() {
        var colorr = ["#008000", "#e0ffc1", "#ffc1e1", "#cc0000"];

        var sp = document.getElementById('span1');
        sp.style.backgroundColor = colorr[0];
    }



And add the function load() in onload property of body tag.

you can use this in html and below in ts or js file

<div [style.background]="getColor(criteria)" >

     switch (para) {    
      case "abc": return '#7C8DFF'; 
      case "xyz": return '#5C2DFD'; 
    }
发布评论

评论列表(0)

  1. 暂无评论