如何在 Less 中使用开始选择器

bum*_*ang 2 css-selectors less

我将创建一个较少的代码,background-color根据它的类为元素提供不同的代码。这将用于附件列表,因此类名基于附件扩展名。

我确实支持一些典型的扩展:

.label{
    &.label-pdf{
        background-color: #c70000;
    }

    &.label-doc, &.label-docx, &.label-odt{
        background-color: #157efb;
    }

    &.label-xls, &.label-xlsx, &.label-calc{
        background-color: #069e00;
    }

    &.label-ppt, &.label-pptx, &.label-odp{
        background-color: #9e3c15;
    }

    &.label-jpg, &.label-png, &.label-gif, &.label-png, &.label-ttf{
        background-color: #95009e;
    }
}
Run Code Online (Sandbox Code Playgroud)

但问题是有一些不寻常的扩展,或类似甚至文件:jpgjpegdocdocx,这就是为什么我想用表达来自CSS。在纯 CSS 中,我可以使用:

    .label.[class^="label-"]{
        background-color: rgba(0,37,100,0.4);
    }
Run Code Online (Sandbox Code Playgroud)

并将此代码放在开头,以便其他类可以覆盖此代码。但不幸的是,这个标志^(我想)正在破坏我的 Less 编译。我一直在尝试做这样的事情:

~".label.[class^='label-']{
    background-color: rgba(0,37,100,0.4);
}"
Run Code Online (Sandbox Code Playgroud)

.label{
    &.~"[class^='label-']"{
        background-color: rgba(0,37,100,0.4);
    }
}
Run Code Online (Sandbox Code Playgroud)

但仍然无法正常工作。那么可以使用这个选择器吗?

Har*_*rry 5

它不起作用是因为您的语法似乎是错误的,而不是因为 Less 有任何问题。

在下面的代码是因为无效.的之间存在labelclass^="label-"]。属性选择器不需要.在它们之前。仅对类选择器是必需的。

.label.[class^="label-"]{
    background-color: rgba(0,37,100,0.4);
}
Run Code Online (Sandbox Code Playgroud)

正确的版本如下:

.label[class^="label-"]{
    background-color: rgba(0,37,100,0.4);
}
Run Code Online (Sandbox Code Playgroud)

所以在 Less 方面,如果你想要嵌套,它会如下:

.label{ 
    &[class^='label-']{
        background-color: rgba(0,37,100,0.4);
    }
}
Run Code Online (Sandbox Code Playgroud)

.label.[class^="label-"]{
    background-color: rgba(0,37,100,0.4);
}
Run Code Online (Sandbox Code Playgroud)
.label[class^="label-"]{
    background-color: rgba(0,37,100,0.4);
}
Run Code Online (Sandbox Code Playgroud)


另一件要注意的事情是^=is a 以选择器开头,因此当您的元素有多个类时,类似的类label-应该是列表中的第一个类,而不是label. 如果我们做label的第一类,那么(就像看到下面摘录),它不会工作,因为那么类不会启动 label-

如果列表中的第一个类确实是,label那么您应该考虑使用*=(contains) 选择器。但是,使用含有选择时一定要小心,因为它有时会选择像那些类无关的元素label-notnot-label等等。

.label{ 
    &[class^='label-']{
        background-color: rgba(0,37,100,0.4);
    }
}
Run Code Online (Sandbox Code Playgroud)
.label.[class^="label-"] {  /* this won't work */
  background-color: rgba(0, 37, 100, 0.4);
}

.label[class^="label-"] {  /* this will */
  color: green;
}
Run Code Online (Sandbox Code Playgroud)