gpt4 book ai didi

javascript - 变量持有样式值无法更改

转载 作者:行者123 更新时间:2023-12-02 14:12:51 26 4
gpt4 key购买 nike

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

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
}

关于javascript - 变量持有样式值无法更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39353102/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com