这种方法为什么无法修改transform的translate?

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>

#aaa{
  width: 100px;height: 100px;
  background-color: orange;
  transform: translateX(150px);
}

</style>
</head>
<body>

<div id="aaa">
</div>

<script>

let a = document.querySelector('#aaa')
let aStyle = window.getComputedStyle(a)
console.log(aStyle.transform);
function set() {
  setTimeout(() => {
    aStyle.style.transform= "translateX(50px)";
}, 1000);
}
set()

</script>
</body>
</html>

阅读 2.2k
2 个回答

不该是 aStyle.style.transform = 'translateX(50px)'
应该是 a.style.transform = 'translateX(50px)'
然后考虑兼容性,把 webkitTransform 也写上

The returned object is the same CSSStyleDeclaration type as the object returned from the element's style property. However, the two objects have different purposes:
  • The object from getComputedStyle is read-only, and should be used to inspect the element's style — including those set by a <style> element or an external stylesheet.
  • The _element_.style object should be used to set styles on that element, or inspect styles directly added to it from JavaScript manipulation or the global style attribute.
  1. getComputedStyle返回的是只读的
  2. 需要element.style方式更新
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题