据我所知,您将无法将样式应用于列。
不过,您可以尝试使用渐变作为背景,使第 3 列和第 4 列变成另一种颜色。
#columns {
background: -webkit-linear-gradient(left, rgba(0,0,0,0) 50%, blue 50%);
/*... appropriate css for other browser engines*/
}
更新了 jsFiddle http://jsfiddle.net/8fKs5/4/更新了所有浏览器支持渐变
- 编辑 -
由于实际上的目的是更改文本颜色而不是第三列和第四列的背景,因此需要一些额外的想法。
目前似乎无法将样式应用于容器内的单个列。更改特定列中文本颜色的一种可能的解决方法是将每个单词放在span
。然后使用 JavaScript 迭代单词并确定新列的开始位置。为第三列中的第一个元素分配一个新类将可以使用不同的文本颜色设置该元素和以下同级元素的样式。
由于容器是响应式布局的一部分,并且大小可能会发生变化,因此必须在调整大小事件上重新运行脚本以适应列宽的变化。
代码示例的目的是概述如何实现这样的解决方案,并且应该对其进行改进以用于实际应用程序(例如span
每次都会重新创建 sstyleCols
正在运行,大量控制台输出...)。
JavaScript
function styleCols() {
// get #columns
var columns = document.getElementById('columns');
// split the text into words
var words = columns.innerText.split(' ');
// remove the text from #columns
columns.innerText = '';
// readd the text to #columns with one span per word
var spans = []
for (var i=0;i<words.length;i++) {
var span = document.createElement('span');
span.innerText = words[i] + ' ';
spans.push(span);
columns.appendChild(span);
}
// offset of the previous word
var prev = null;
// offset of the column
var colStart = null;
// number of the column
var colCount = 0;
// first element with a specific offset
var firsts = [];
// loop through the spans
for (var i=0;i<spans.length;i++) {
var first = false;
var oL = spans[i].offsetLeft;
console.info(spans[i].innerText, oL);
// test if this is the first span with this offset
if (firsts[oL] === undefined) {
console.info('-- first');
// add span to firsts
firsts[oL] = spans[i];
first = true;
}
// if the offset is smaller or equal to the previous offset this
// is a new line
// if the offset is also greater than the column offset we are in
// (the second row of) a new column
if ((prev === null || oL <= prev) && (colStart === null || oL > colStart)) {
console.info('-- col++', colCount + 1);
// update the column offset
colStart = oL;
// raise the column count
colCount++;
}
// if we have reached the third column
if (colCount == 3) {
// add our new class to the first span with the column offset
// (this is the first span in the current column
firsts[oL].classList.add('first-in-col3');
return;
}
// update prev to reflect the current offset
prev = oL;
}
}
styleCols();
addEventListener('resize', styleCols, false);
CSS
.first-in-col3, .first-in-col3~span {
color: red;
}
jsFiddle http://jsfiddle.net/8fKs5/7/