简体   繁体   English

如何在 JavaScript 中设置元素的 style.top 属性?

[英]How do I set the style.top property of an element in JavaScript?

I must fix a JavaScript source-code, which sets the style.top property of a div element depending upon an integer parameter of a function called index like this:我必须修复一个 JavaScript 源代码,它根据名为 index 的函数的整数参数设置 div 元素的 style.top 属性,如下所示:

div.style.top = (index * 22 + 2)+"px";

For bigger values of index (20, 21, 22,.... 53, 54,...) the value of div.style.top is not accurate anymore, ie it becomes too big, while for small values ( ie index < 10 ) the value of div.style.top calculated like this is OK.对于较大的索引值(20, 21, 22,.... 53, 54,...) div.style.top 的值不再准确,即它变得太大,而对于较小的值(即index < 10 ) 这样计算出来的 div.style.top 的值是可以的。 My idea was to use the already existing HTML element called checkbox, which is visually correct aligned, and take its style.top value like this:我的想法是使用已经存在的名为 checkbox 的 HTML 元素,它在视觉上是正确对齐的,并采用它的 style.top 值,如下所示:

div.style.top = checkbox.style.top

But checkbox.style.top is not defined, although the element checkbox is correctly displayed on the HTML page.但是 checkbox.style.top 没有定义,虽然元素 checkbox 正确显示在 HTML 页面上。

Is there some way to set the value of checkbox.style.top to be equal to the actual absolute position it takes, without knowing what this value is?有没有办法将 checkbox.style.top 的值设置为等于它所采用的实际绝对位置,而不知道这个值是什么?

Use element.offsetTop;使用element.offsetTop; (per MDN): (每个 MDN):

var d = document.getElementById("div1");
var topPos = d.offsetTop;

if (topPos > 10) {
  // object is offset more
  // than 10 pixels from its parent
}

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM