较少的mixin递归错误将像素转换为rems [英] LESS mixin recursion error to convert pixels to rems

查看:65
本文介绍了较少的mixin递归错误将像素转换为rems的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试进行混合以适当地将像素转换为相对em.我希望它足够灵活以允许将任何属性与任意数量的像素值一起使用.

I am trying to make a mixin to propery convert pixels to relative ems. I would like it to be flexible enough to allow any property to be used with any number of pixel values.

有没有关于如何在一个for循环中创建的没有递归错误的情况下将多个值添加到单个属性的想法?

Any ideas on how to add multiple values to a single property without the recursion error I'm creating inside the for loop?

所需的用法示例1:

.pixels-to-rems(font-size; 10);

所需的输出:

font-size: 10px;
font-size: 1rem;

所需的用法示例2:

.pixels-to-rems(padding; 10,0,20,10);

所需的输出:

padding: 10px, 0px, 20px, 10px;
padding: 1rem, 0px, 2rem, 1rem;

这里是mixin.

@baseFontSize: 10px;
.pixels-to-rems(@property, @pxvals) {
    @pxValue: null;
    @remValue: null;

    .for(@pxvals); .-each(@pxval) {
        @pxValue: @pxValue @pxval;
        @remValue: @remValue (@pxval / @baseFontSize);
    }

    @{property}: ~"@{pxValue}px";
    @{property}: ~"@{remValue}rem";
}

.for()混入此处

推荐答案

请参见合并功能.唯一的技巧是merge语句会将值连接到 same 属性规则中,因此您必须通过一些技巧来隔离pxrem规则.例如这样的

See Merge feature. The only trick is that the merge statement will concatenate values into the same property rule, thus you'll have to isolate px and rem rules via some hack. For example like this:

usage {
    .pixels-to-rems(padding, 10 0 20 10);
    .pixels-to-rems(font-size, 50);
}

// impl.:

@base-font-size: 10px;

.pixels-to-rems(@p, @vs) {
    .for(@vs); .-each(@v) {
        @{p}+_:     1px  * @v;
        @{p}@{-}+_: 1rem * @v / @base-font-size;
    }
    @-: ~" ";
}

// .for-each impl. (stripped from the snipped linked in the question)

.for(@array)                 {.for-impl_(length(@array))}
.for-impl_(@i) when (@i > 1) {.for-impl_((@i - 1))}
.for-impl_(@i) when (@i > 0) {.-each(extract(@array, @i))}

查看全文

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