CSS Calc中能否给一个值添加单位?

16

我现在正在使用JavaScript将一个值存储在DOM中:

document.documentElement.style.setProperty('--offset', offset+'px')

后来,我将其用作动画计算中的一部分:

@keyframes upanim {
    from    {transform: translate3d(0,calc(var(--offset) - 100vh ),0);}
    to  {transform: translate3d(0,0,0);}
}

现在我想使用同样的值来计算动画的速度,使得速度始终是每秒相同数量的像素:

animation: upanim calc(var(--offset) * 0.002)s cubic-bezier(0, 0, 0.25, 1);

问题在于“px”和“s”,我想把单位放在计算式里面,然后只把值存储在DOM中。这种做法可行吗?
1个回答

41

要在需要像素的属性中使用无单位的CSS变量,您需要将其乘以1px。

width: calc(var(--offset) * 1px);
所以,我认为最好的方法是将变量偏移值设置为没有尺寸,并在使用时添加这些尺寸:
在代码片段中,将鼠标悬停在body上可以看到元素以恒定速度移动:
#t1 {
  --offset: 10;
}
#t2 {
  --offset: 20;
}
#t3 {
  --offset: 40;
}

.test {
  width: 100px;
  height: 40px;
  margin: 5px;
  background-color: antiquewhite;
  transform: translateX(calc(var(--offset) * 1vh));
}

body:hover .test {
  animation: move calc(var(--offset) * 0.2s) linear forwards;
  background-color: lightgreen;
}

@keyframes move {
    from  {transform: translateX(calc(var(--offset) * 1vh));}
      to  {transform: translateX(0);}
}
<div class="test" id="t1">ONE</div>
<div class="test" id="t2">TWO</div>
<div class="test" id="t3">THREE</div>
I am sorry, but your request is incomplete and does not provide any context or content for me to translate. Please provide more specific information or text that needs to be translated.

很酷,但这能与vh一起使用吗? calc((var(--offset) - 100vh) * 0.0004s) - Himmators
1
我认为这是不可能完成的。将vh转换为像素的计算部分是在处理尺寸的属性内完成的,因此很难想象它能在您的上下文中工作。我会考虑一下,也许我可以找到一些解决方案。 - vals
1
我知道您的需求可能不同,但据我所知,我已发布了最好的解决方案。 - vals
我会给你点赞,但这并不是对我的问题的真正回答,所以我不能批准它... - Himmators

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接