在屏幕更改大小时管理列表分隔符(媒体查询)

Manage liste separator while the screen change size (media query)

我尝试在列表的每个元素之间管理分隔符(如“-”)。 当我们只有一根线的时候比较简单,但我不能超过一根线。

当网站在大屏幕上显示时我有:

示例 居中对齐

Listitem1 - listitem2 - listitem3 - ... - listitemX

没有分隔符“-”的最后一项

html

<p>
    <a>listitem1</a>
    <a>listitem2</a>
    <a>listitem3</a>
    <a>listitem4</a>
    <a>listitem5</a>
    <a>listitem6</a>
    <a>listitem7</a>
...
    <a>listitemX</a>
</p>

CSS

a:nth-child(n+2)::before {
  content: " - "
}

这在 CSS 中相对容易使用 :: before 从第二个 child...

但是对于媒体查询,当我的屏幕缩小并且同一个列表跨越多行时,我想从每行中删除最后一个“-”分隔符。

示例 居中对齐

Listitem1 - listitem2 - listitem3 - listitem4 (without the separator here)
Listitem5 - listitem6 - listitem6 - listitem8 (without separator here either)
Listitem9 - etc ...

有人有想法吗? 先感谢您。塞巴斯蒂安

似乎没有一个纯粹的 CSS 解决方案,但您可以使用一些 JS 来设置或取消设置 class 基于一个项目是否是一行中的第一个.

这里我将文本颜色设置为透明而不是将内容设置为“”,因为更改内容会影响宽度,然后它会随着它跳转 wraps/resizes。

a.firstInLine::before {
    color: transparent;
}

Javascript 遍历节点并检查它是否在页面上低于前一个节点。如果是(误差很小),它会设置 class firstInLine:

function calcY() {
    document.querySelectorAll("p a").forEach((n, i, nodes) => {
        if(i > 0) {
            const thisY = n.getClientRects()[0].y;
            const prevY = nodes[i - 1].getClientRects()[0].y;
            
            if(thisY - prevY > 4) {
                n.classList.add("firstInLine");
            }
            else {
                n.classList.remove("firstInLine");
            }
        }
    });
}

window.addEventListener("resize", calcY);
calcY();

我应该补充一点,还有一些其他 CSS 的东西需要设置。我们不希望它换行,为了让 getClientRects 正常工作,它不能是纯内联元素,所以:

a {
    white-space: nowrap;
    display: inline-block;
}

CodePen