如何使用 SASS 等颜色但在 Ruby 中进行数学运算?
在 SASS 中我可以做:
!pink = #ff43a7
!darker_pink = !pink - #333333
我想在 Ruby 中做同样的事情。
In SASS I can do:
!pink = #ff43a7
!darker_pink = !pink - #333333
I'd like to the same in Ruby.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
可以通过在值前添加
0x
来在 Ruby 中表示十六进制:color helper
在 ERb 模板
输出中的用法
Hex can be represented in Ruby by prefixing your value with
0x
:color helper
Usage in ERb template
Output
使用 Sass 模块
如果您已经拥有 Sass 库,则可以实例化并使用其对象。
例如:
必须有一种内置方法可以将像
#00FF00
这样的十六进制字符串转换为Color
对象,但没有看到,我写了这个函数:Use the Sass module
If you already have the Sass library, you can instantiate and work with its objects.
For instance:
There must be a built-in way to turn hexadecimal strings like
#00FF00
intoColor
objects, but not seeing one, I wrote this function:在 Sass 中添加/减去颜色的基本方法是无意义的,只有在使用灰度调整时才真正有效。这就是为什么在 Sass 3 中,我们现在完全支持 HSL 域中的操作,这与人们对颜色的看法密切相关。
由于 Sass 是用 Ruby 编写的,因此您至少可以阅读我们的代码来了解发生了什么。
这是 颜色类,以及 < a href="http://github.com/nex3/haml/blob/master/lib/sass/script/functions.rb" rel="nofollow noreferrer">对其进行操作的函数。
这确实是不平凡的代码。为什么不直接使用 Sass 呢?
The basic approach of adding/subtracting colors in Sass is nonsense and only really works when using a gray adjustment. That's why in Sass 3 we now have full support of operations in the HSL domain which maps closely to the way people think about colors.
Since Sass is written in Ruby, you can at least read our code to see what's going on.
Here's the Color class, and the functions that operate on them.
It really is non-trivial code. Why not just use Sass?
为了完善@macek的答案,遵循@drawnownward和@lpsquiggle的愿望:
你可以制作两个助手,如下所示:
优点:如果你定义了一个低值的颜色十六进制(这里是0到3之间),这些将被碰撞在减法之前,它们最终会变成 0,而不是环绕并变成 c、d、e 或 f(这会给你一个意想不到的颜色)。它只对每个 #rrggbb 对中的第一个值执行此操作,因此 #313131 变为 #0d0d0d,这在技术上是不正确的,但它比 #fdfdfd 好得多,所以这似乎是一个足够好的妥协,因为你会想要在其他情况下保留第二个值。
那么,在您的 Erb 模板中,您可以这样写:
而不是:
希望对某人有帮助。
To refine @macek's answer, following @drawnownward's and @lpsquiggle's wishes:
You can make two helpers, like so:
The advantage: if you've defined a color hex with low values (between 0 and 3, here), these will be bumped up before the subtraction, so that they end up as 0 afterward, instead of wrapping around and becoming c, d, e, or f (which would give you a color you didn't expect). It only does this for the first value in each #rrggbb pair, so #313131 becomes #0d0d0d, which isn't technically correct, but it's much better than #fdfdfd, so it seems like a good enough compromise, since you'll want to keep those second values in other cases.
In your Erb template, then, you would write this:
Instead of:
Hope that helps someone.
我刚刚遇到一些问题,我想将一组颜色分配给不同的色调。 SASS 源没有多大帮助,因为我没有找到从 HSV 获取 RGB 的方法。
彩色宝石有我需要的东西。
我写了这个助手:
I just came across something where I wanted to distribute colors for a set across different hues. The SASS source didn't help much because I didn't see a way to get RGB from HSV.
The color gem had what I needed.
I wrote this helper: