变量持有风格值不能改变

variable holding style value can't be changed

我很好奇一个简单的问题。这是代码:

var square = document.getElementById('square')
var left = square.style.left

function moveNoVariable() {
  square.style.left = "100px" // works
}

function moveWithVariable() {
  left = "100px" // doesn't work
}

moveNoVariable()
#square {
  width: 20px;
  height: 20px;
  border: 1px solid black;
  background-color: red;
  position: relative;
}
<div id="square"></div>

我只是想知道为什么如果我使用 "left" 即使它存储了正确的值,样式也不会改变。

谢谢。

square.style.left 是一个字符串。如果将字符串放入变量中,变量将存储给定字符串的副本。如果将对象放入变量中,变量将引用原始对象。所以你可以这样做,例如:

var square = document.getElementById('square')
var style = square.style

function moveNoVariable() {
  square.style.left = "100px" // works
}

function moveWithVariable() {
  style.left = "100px" // will work
}