2016-09-06 43 views
0

我很好奇一個簡單的問題。下面是代碼:變量保持樣式值不能更改

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>

我只是想知道爲什麼,如果我用「左」,即使它被存儲正確值的風格不會改變。

謝謝。

回答

2

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 
} 
+0

這。這是答案。我正在刪除我的,因爲它只是令人困惑。 –

+0

完美,現在就明白了。 – Zzgooloo