在Less中使用未知值作为选择器 [英] Use unknown values as selectors in Less

查看:75
本文介绍了在Less中使用未知值作为选择器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出此标记:

<div class="parent" data-active="typeA">
    <div class="child" data-show="typeA">Show only when parent=typeA</div>
    <div class="child" data-show="typeB">Show only when parent=typeB</div>
    <div class="child" data-show="typeC">Show only when parent=typeC</div>
</div>

我正在尝试编写一个全局适用的LESS规则,该规则仅在其data-show属性与父级的data-active属性匹配时显示一个子级.

I'm trying to write a globally applicable LESS rule that only displays a child when its data-show attribute matches the parent's data-active attribute.

类似这样的东西:

.parent {
    .child { display:none; }
    &[data-active="?"] .child[data-show="?"] { display:block; }
}

...其中,?不应为固定值,而应是无论该值如何都适用的条件,只要它们相同即可.

...where ? should not be a fixed value, but a condition that applies no matter the value, as long as they are the same.

有什么想法吗?

推荐答案

随着LESS被编译为CSS,并且在CSS中没有通用的方法,我只想出一个解决方案,要求您了解所有可能的 type .

As LESS gets compiled to CSS and there is no generic approach for doing this in CSS, I only come up with a solution that requires you to know every possible type.

.parent {
    .child { display: none; }     
    &[data-active="typeA"] {
        .child[data-show="typeA"] { display: block; }
    }
    &[data-active="typeB"] {
        .child[data-show="typeB"] { display: block; }
    }
    &[data-active="typeC"] {
        .child[data-show="typeC"] { display: block; }
    }
}

根据您的喜好并为避免重复,您还可以定义一个用于添加不同类型的函数.

Depending on your preferences and to avoid redundancy you could also define a function for adding the different types.

.parent {
    .child { display: none; }
    .addType("typeA");
    .addType("typeB");
    .addType("typeC");    
}

.addType(@type) {
    &[data-active="@{type}"] {
        .child[data-show="@{type}"] { display: block; }
    }
}

如果要使其更通用,可以定义一个类型数组,并为每个这样的类型调用.addType:

And if you want to make this even more generic, you could define an array of types and call .addType for each of the types like this:

@types: "typeA", "typeB", "typeC";

.parent {
    .child { display: none; }
    .-(@i: length(@types)) when (@i > 0) {
        @type: extract(@types, @i);
        .addType(@type);
        .-((@i - 1));
    } .-;
}

.addType(@type) { /* see above */ }

这篇关于在Less中使用未知值作为选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆