LESS CSS - &:focus 在变量选择器中不起作用

LESS CSS - &:focus not working in variable selector

我的 .less 样式表中有以下代码。

@text-inputs: input[type=text], input[type=password], input[type=email], input[type=number];
@shade: rgba(0, 0, 0, 0.1);

.highlight {
    background: @shade;
}

.input-highlight {
    @{text-inputs} {
        .highlight;
    }
}

.input-highlight-subtle {
    @{text-inputs} {
        &:focus {
            .highlight;
        }
    }
}

我的HTML:

<body class="input-highlight-subtle">
    <input type="text" placeholder="Type Here" />
    <input type="password" placeholder="Type Here"/>    
</body>

上面CSS的结果:即使我没有悬停在输入上,输入的背景也是@shade颜色。我检查了我的浏览器开发者工具,显然它生成了这样的代码:

.highlight {
  background: rgba(0, 0, 0, 0.1);
}
.input-highlight-subtle input[type=text], input[type=password],  input[type=email], input[type=number]:focus {
  background: rgba(0, 0, 0, 0.1);
}

那我该如何解决呢?

编辑:

基本上我想要这样的输出:

.input-highlight-subtle input[type="text"]:focus, .input-highlight-subtle input[type="password"]:focus, .input-highlight-subtle  input[type="email"]:focus, .input-highlight-subtle input[type="number"]:focus {
    .highlight;
}

如何使用更少的代码实现 ^? (双关语)

你可以试试:

.text-inputs() {
    input[type=text], input[type=password],input[type=email], input[type=number]{        
        .text-inputs-properties();
    }
}

@shade: rgba(0, 0, 0, 0.1);

.highlight {
    background: @shade;
}

.input-highlight {
    .text-inputs();
    .text-inputs-properties() {       
        .highlight;
    }  
}

.input-highlight-subtle {
    .text-inputs();
    .text-inputs-properties() {
        &:hover{
            .highlight;
        }
    }      
}

感谢@seven-phases-max 的回答Focused selector in variable . How to do that stuff in LESS like in SCSS

我刚刚根据您的情况对其进行了调整,您可以在此处使用此 FIDDLE 示例,希望这对您有所帮助

EDIT1: 我找到了 this @scottgit comment 我认为也应该考虑

" 有一种变通方法可以使用 LESS 1.7 的功能将属性分配给变量中定义的一组选择器。考虑一下:"

//I modified the code a litter bit for your case   

@shade: rgba(0, 0, 0, 0.1);

@inputs: {input[type=text], input[type=email], input[type=password], input[type=number] {.getProps()}};
@pseudo: ~':hover';
@props: { background: @shade;};

.input-highlight-subtle{
    .setProps(@selectors; @props; @extension: ~'') {
        @selectors();
        .getProps() {
            &@{extension} { @props(); }
        }
    } 

    .setProps(@inputs; @props; @pseudo);
}

"So I can assign a pseudo class if I want or not, and pass a set of properties as needed. The key is to put the mixin .getProps() call into the block that is defining the selectors for variable @inputs, which is then called as a local mixin inside .setProps() so that the properties get put where we want them. The @extension could be any escaped string to add to each selector as an additional part of the selector string. Above I do :focus as a pseudo class, but I could have done ~' > div + div' as a child and sibling combination, or whatever."

here the jsfiddle example