LESS CSS - &amp ;:焦点不在变量选择器中工作

时间:2015-06-07 16:57:16

标签: html css less

我的.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;
}

如何用LESS代码实现^? (双打目的)

1 个答案:

答案 0 :(得分:1)

您可以尝试:

.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-phase-max的回复Focused selector in variable . How to do that stuff in LESS like in SCSS

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

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

&#34;有一个解决方法是使用LESS 1.7的功能来获得将属性赋值给变量中定义的一组选择器的功能。考虑一下:&#34;

//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);
}

&#34;所以我可以根据需要分配伪类,并根据需要传递一组属性。关键是将mixin .getProps()调用放入定义变量@inputs的选择器的块中,然后将其作为.setProps()内的局部混合调用,以便将属性放在何处我们想要他们。 @extension可以是要添加到每个选择器的任何转义字符串,作为选择器字符串的附加部分。上面我做:focus作为一个伪类,但我可以做~' > div + div'作为一个孩子和兄弟组合,或其他什么。&#34;

here the jsfiddle example