Javascript:在条带之间使用分隔符构建CSS线性渐变

时间:2019-07-15 10:23:00

标签: javascript css

我有这段代码用于通过颜色数组(未知长度)构建线性渐变:

const colors = ['red', 'green', 'violet'];
const strips = [];
let start = 0;
let end  = 0;
const stripPerc = Math.ceil(100 / colors.length);
for (let i = 0; i < colors.length; i++) {
  const color = colors[i];
  start = end;
  end   = start + stripPerc;

  if ( end > 100 ) {
    end = 100;
  }

  let strip = color + ' ';
  strip += start + '% ';
  strip += end + '% ';

  strips.push(strip.trim());
}
document.getElementById('foo').style.backgroundImage = 'linear-gradient(135deg, ' + strips.join(',') + ')';
div {
  display: block;
  width: 100%;
  height: 50px;
}
<div id="foo"></div>

我想在颜色之间添加一个小的(1%)白色条纹:

const colors = ['red', 'green', 'violet'];
const strips = [];
let start = 0;
let end  = 0;
const stripPerc = Math.ceil(100 / colors.length);
for (let i = 0; i < colors.length; i++) {
  const color = colors[i];
  start = end;
  end   = start + stripPerc;

  if ( end > 100 ) {
    end = 100;
  }

  let strip = color + ' ';
  strip += start + '% ';
  strip += end + '% ';

  strips.push(strip.trim());
  
  strips.push(' white ' + end + '% '+ (end+1) +'%');
  end++;
}
document.getElementById('foo').style.backgroundImage = 'linear-gradient(135deg, ' + strips.join(',') + ')';
div {
  display: block; 
  width: 100%;
  height: 20px;
}
<div id="foo"></div>

它可以工作,但是现在总长度超过100%。如何解决?

2 个答案:

答案 0 :(得分:2)

我对代码进行了一些重构,但是逻辑与预期相同-您应该考虑白色条纹的宽度来计算彩色条纹的宽度https://jsbin.com/supikoz/edit?html,js,output

const coloredWidth = 100 - stripWidth * (colors.length - 1);
const stripPerc = Math.ceil( coloredWidth / colors.length);

答案 1 :(得分:0)

您可以为此使用flexbox。根据您的需要,可以对其进行样式设置或添加空白。诀窍是在两者之间使用空格。我建议使用js进行计算,并使用CSS进行放置。

const colors = ['red', 'green', 'violet'];
const stripPerc = Math.ceil(100 / colors.length) - 1;

colors.forEach(color => {
  let strip_element = document.createElement('div');
  strip_element.style.background = color;
  strip_element.style.width = stripPerc + '%';
  
  document.getElementById('flex').appendChild(strip_element);
})
#flex {
  display: flex;
  justify-content: space-between;
  width: 100%;
  height: 50px;
  position:relative;
}
<div id='flex'>
</div>