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