我可以将单位添加到CSS Calc中的值吗?

Him*_*ors 3 css3

我现在正在使用javascript在DOM中存储值:

document.documentElement.style.setProperty('--offset', offset+'px')
Run Code Online (Sandbox Code Playgroud)

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

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

我现在想使用相同的值来计算该动画的速度,以便该速度始终是相同的像素/秒数:

animation: upanim calc(var(--offset) * 0.002)s cubic-bezier(0, 0, 0.25, 1);
Run Code Online (Sandbox Code Playgroud)

问题是'px'和's',我想在计算中添加单位,然后将值存储在DOM中。这可能吗?

val*_*als 5

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

width: calc(var(--offset) * 1px);
Run Code Online (Sandbox Code Playgroud)

因此,我认为最好的方法是设置无尺寸的变量偏移量,并在使用时添加以下尺寸:

在代码段中,将鼠标悬停在主体上以查看元素以恒定速度运动:

width: calc(var(--offset) * 1px);
Run Code Online (Sandbox Code Playgroud)
#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);}
}
Run Code Online (Sandbox Code Playgroud)