我应该如何引用document.getComputedStyle中的特定元素

How should I refer to a specific element in document.getComputedStyle?

本文关键字:getComputedStyle 元素 document 何引用 引用 我应该      更新时间:2023-09-26

我正在制作一个游戏,其中有一个可拖动的对象,我想实时存储它的实际位置。有人告诉我应该使用getComputedStyle,但它只在我使用的情况下有效

var computedStyle = getComputedStyle(document.body, null)

我的意思是如果我加

document.write(computedStyle.marginTop)

它起作用,并写入上边距的值。但是我需要一个div元素的位置。。我试过使用

    var place = document.getElementById("draggable");
    var computedStyle = getComputedStyle(place, null);
    document.write(computedStyle.marginTop);

但它什么也没做。我也试过

var computedStyle = getComputedStyle(document.getElementById("draggable"), null);

但它也不起作用。

有人能帮我弄清楚我应该如何引用id为"draggable"的div元素吗?

开发人员文档位于https://developer.mozilla.org/en-US/docs/Web/API/Window.getComputedStyle似乎表明以下应该成功:

var elem1 = document.getElementById("elemId");
var style = window.getComputedStyle(elem1, null);

因此,尝试将window.添加到getComputedStyle子句中,并检查div的名称是否正确。

如果这两件事都没有帮助,请检查javascript控制台是否有错误。