javascript实战 : 简单的颜色渐变

HTML

<div id="color"></div>

CSS

.item{
  display:inline-block;
  margin:10px;
  width:100px;
  height:30px;
}

JAVSCRIPT

/*
  颜色渐变DEMO
  目前支持红色系和蓝色系 
  5个及以下使用预设颜色
  5个以上根据最大最小值进行动态计算
*/

function getItemColors (colorLevel=5, color_string='red') { 
  function setter (color_string) {
    if (!color_string) {
        color_string = 'red'
    }
    if (color_string === 'red') {
        red = 244,green = 0, blue = 0; 
        maxRed = 244 ,maxGreen = 110,maxBlue = 110; 
    }
    if (color_string === 'blue') {
        red = 94,green = 48, blue = 183; 
        maxRed = 134 ,maxGreen = 108,maxBlue = 184; 
    }
  }
  
  var red, green, blue, maxRed, maxGreen, maxBlue
  var colors= [];
  var base_lavel = 5
  
  setter(color_string)
  var level = (function(colorLevel){
    return Math.max(colorLevel, base_lavel)
  })(colorLevel) ; 
  var count = level
  while(count--) { 
    colors.push( 'rgb('+red +','+green+','+blue+')'); 
    red += parseInt(maxRed/level); 
    green += parseInt(maxGreen/level); 
    blue += parseInt(maxBlue/level); 
  } 
  if (colorLevel < base_lavel) {
      switch(colorLevel) {
       case 0:
          return colors
       case 1:
          return [colors[2]]
       case 2:
          return [colors[2], colors[3]]
       case 3:
          return [colors[1], colors[2], colors[3]]
       case 4:
          return [colors[1], colors[2], colors[3], colors[4]]
       case 5:
          return colors
       default:
          return colors
      } 
  } else {
     return colors; 
  }
} 

var arr = getItemColors(5, 'blue')
var all = ""
var html = ['<span class="item" style="background:','"></span>']

arr.forEach(function(item){
  var h = html[0] + item + html[1]
  all += h
})

console.log(arr)

document.getElementById('color').innerHTML = all

效果:

以上。

 

posted on 2019-07-25 15:47  fox_charon  阅读(706)  评论(0编辑  收藏  举报

导航