我可以在 Javascript 中使用 CSS calc 吗?

Can I use CSS calc within Javascript?

我可以在 JavaScript 中设置位置时使用 css calc() 功能吗?

ePopup.style.top = "calc(100px - 1.5em)";

是的,calc() 将在 javascript 中设置样式时起作用。

工作示例:

var innerDiv = document.getElementsByClassName('inner-div')[0];

function growInnerDiv() {
    innerDiv.style.setProperty('width', 'calc(100% + 224px)');
}

innerDiv.addEventListener('click', growInnerDiv, false);
.outer-div {
    display: inline-block;
    width: 200px;
    height: 100px;
    padding: 12px;
    border: 1px solid rgb(255,0,0);
    background-color: rgb(255,255,0);
}

.inner-div {
    width: 100px;
    height: 100px;
    color: rgb(255, 255, 255);
    font-weight: bold;
    text-align: center;
    line-height: 100px;
    font-family: arial, helvetica, sans-serif;
    background-color: rgb(255,0,0);
    cursor: pointer;
    transition: all 0.5s linear;
}
<div class="outer-div">
    <div class="inner-div">Click Me</div>
<div>

当您将 calc 与相同类型的单位一起使用时,会发生一些有趣的事情,例如10px + 5px。它通过将它放到元素上的过程简化为 15px

因此,为了扩展 rounin 的出色答案,这里有一些实际行为的示例:

function growDiv(e) {
        const thisDiv = e.target;
        const x = 100;
        const y = 42;
        const z = 69;
        let widthVal;

        if (thisDiv.id == "simplifies") {
          widthVal = `calc(${y + z}px + ${x}px + ${y}px)`;
        } else if (thisDiv.id == "mixed-units") {
          widthVal = `calc(0em + ${y + z}px + ${x * 2}px + ${y}px)`;
        } else if (thisDiv.id == "variables") {
          thisDiv.style.setProperty("--x", x + "px");
          thisDiv.style.setProperty("--y", y + "px");
          thisDiv.style.setProperty("--z", z + "px");
          widthVal = "calc((var(--x) * 2) + var(--y) + (var(--z) * 2))";
        }

        thisDiv.style.width = widthVal;
        thisDiv.innerHTML =
          `input: ${widthVal}<br>style:${thisDiv.style.width}`;
      }

      document
        .querySelectorAll("div")
        .forEach((el) => el.addEventListener("click", growDiv, false));
.inner-div {
        background-color: hotpink;
        color: white;
        font-weight: bold;
        height: 100px;
        margin-bottom: 5px;
        text-align: center;
        transition: all 0.5s linear;
        width: 100px;
      }
<div class="inner-div" id="simplifies">simplifies<br />1) Click Me</div>
<div class="inner-div" id="mixed-units">mixed-units<br />2) Click Me</div>
<div class="inner-div" id="variables">variables<br />3) Click Me</div>
    

Div 1 具有所有相同的单位,因此简化了。

Div 2 有一个token 0em 单位,这对计算没有影响,但强制完整表达式通过。

Div 3 是我最喜欢的,因为它有点自我记录。我这样做是因为我有点健忘,它让我明白了 为什么 我将该元素设置为 728.3 高,而不仅仅是我所做的