我有一个带有4个css列的div,我想选择第3和第4列使文本稍暗,因为我在文本和背景图像之间没有很好的对比.这可能吗?我可以接受任何css或js解决方案.
这是demo.
– 编辑 –
似乎不可能找到伪块的选择器(如果我可以说)但是我仍然需要找出一种创建响应块(如列)的方法,只要浏览器是这样,它就会平均分割文本(宽度)调整大小.
解决方法
据我所知,您将无法将样式应用于列.
然而,你可以尝试使用渐变作为背景,使第3列和第4列成为另一种颜色.
然而,你可以尝试使用渐变作为背景,使第3列和第4列成为另一种颜色.
#columns {
background: -webkit-linear-gradient(left,rgba(0,0) 50%,blue 50%);
/*... appropriate css for other browser engines*/
}
updated jsFiddle
使用所有浏览器支持渐变更新
– 编辑 –
因为意图实际上是改变文本颜色而不是第三和第四列的背景一些额外的想法.
目前,似乎无法将样式应用于容器内的单个列.更改特定列中文本颜色的一种可能解决方法是将每个单词放在跨度中.然后使用JavaScript迭代单词并确定新列的开始位置.为第三列中的第一个元素分配一个新类,可以使用不同的文本颜色设置此样式和以下兄弟.
由于容器是响应式布局的一部分,并且可能会更改大小,因此必须在resize事件上重新运行该脚本以考虑更改列宽.
代码示例的目的是概述如何实现这样的解决方案,并且应该在实际应用程序中进行改进(例如,每次运行styleCols时都会重新创建跨度,大量的控制台输出……).
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