简体   繁体   English

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

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

I am making a game where there is a draggable object and I would like to store its actual place in real time. 我正在制作一个有可拖动对象的游戏,我想实时存储其实际位置。 I was told I should use getComputedStyle but it only works in case I use 有人告诉我我应该使用getComputedStyle,但是它只能在我使用的情况下起作用

var computedStyle = getComputedStyle(document.body, null)

I mean if I add 我的意思是如果我加上

document.write(computedStyle.marginTop)

it works and it writes the value of the top margin. 它可以正常工作,并写出上边距的值。 But I need a div element's place.. I tried using 但是我需要一个div元素的位置。

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

but it does nothing. 但它什么也没做。 I also tried 我也试过

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

but it also did not work. 但它也没有用。

Can somebody please help me out how should I refer to the div element with the id "draggable"? 有人可以帮帮我,我应该如何引用id为“ draggable”的div元素?

The developer docs at https://developer.mozilla.org/en-US/docs/Web/API/Window.getComputedStyle seem to indicate that the following should succeed: https://developer.mozilla.org/zh-CN/docs/Web/API/Window.getComputedStyle上的开发人员文档似乎表明以下内容应该成功:

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

So, try adding window. 因此,尝试添加window. to your getComputedStyle clause, and check that your div is named correctly. 到您的getComputedStyle子句,并检查您的div是否正确命名。

If neither of those two things help, check your javascript console for errors. 如果这两件事都没有帮助,请检查您的JavaScript控制台是否有错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何获取div子元素的ComputedStyle? - How to getComputedStyle of sub-element of div? Javascript 如何在 an:active 伪元素上使用 getComputedStyle? - Javascript how to use getComputedStyle on an :active pseudo element? Javascript 如何记录应该是特定类型的 Object 的变量 - Javascript how do I document a variable that should be an Object of a specific type 在Jquery中如何引用document.createElement创建的javascript元素 - In Jquery how to refer javascript's element created by document.createElement 我如何引用刚刚在Javascript中创建并获得其值的特定html元素? - How would I refer to a specific html element that was just made in Javascript and get its value? 如何在表单中引用span元素? - How can i refer to a span element in a form? 如何在DOMParser生成的文档中使用getComputedStyle(没有defaultView或window对象)? - How to use getComputedStyle with DOMParser produced document (no defaultView or window objects)? MongoDB中的多对多-如何引用另一个文档的子文档 - Many to Many in MongoDB - How do I refer to the subdorument of another document 如何在另一个函数中引用父元素? - How can I refer to the parent element once inside another function? js如何在getComputedStyle规则中获取源CSS规则 - js how can I get the source css rule in getComputedStyle rule
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM