简体   繁体   中英

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:

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. 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:

div.style.top = checkbox.style.top

But checkbox.style.top is not defined, although the element checkbox is correctly displayed on the HTML page.

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?

Use element.offsetTop; (per MDN):

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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