我有一个带有 4 个 css 列
的 div
,我想选择第 3 和第 4 列以使文本稍微暗一些,因为我没有文本和 background-image
之间的良好对比。这可能吗?我可以接受任何 css 或 js 解决方案。
这是 demo .
--编辑--
似乎不可能找到伪 block 的选择器(如果我可以说的话)但是我仍然需要找出一种创建响应 block (如列)的方法来拆分每当调整浏览器大小时,文本均等(宽度)。
最佳答案
据我所知,您无法将样式应用于列。 但是,您可以尝试使用渐变作为背景,使第 3 列和第 4 列成为另一种颜色。
#columns {
background: -webkit-linear-gradient(left, rgba(0,0,0,0) 50%, blue 50%);
/*... appropriate css for other browser engines*/
}
updated jsFiddle 更新所有浏览器支持渐变
-- 编辑 --
因为我们的意图实际上是改变文本颜色而不是第三和第四列的背景,所以一些额外的想法。
目前似乎无法将样式应用于容器内的单个列。更改特定列中文本颜色的一种可能的解决方法是将每个单词放在 span
中。然后使用 JavaScript 遍历单词并确定新列的开始位置。为第三列中的第一个元素分配一个新类可以使用不同的文本颜色设置此元素和后续元素的样式。
由于容器是响应式布局的一部分并且可能会改变大小,因此必须在调整大小事件中重新运行脚本以解决列宽变化的问题。
代码示例的目的是概述如何实现这样的解决方案,并且应该改进以在实际应用程序中使用(例如,span
每次都被重新创建 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;
}
关于javascript - 我可以选择第 n 个 css 列吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15270509/