简体   繁体   English

JavaScript定位元素

[英]Javascript positioning element

I try to create input controls dynamically , works fine apart from the positioning, for some reason I cant put the elements under the previous one, because I'm unable to get "style.top" property. 我试图动态地创建输入控件,除了定位之外还可以正常工作,由于某种原因,我无法将元素放在上一个元素的下面,因为我无法获得“ style.top”属性。 What I'm doing wrong and how can I fix it? 我在做什么错,我该如何解决?

the HTML code: HTML代码:

<div id='div_attach' class='scrollbox' style='top: 380px; height: 65px; left: 100px; right: 135px;'>
  <a href='goes_nowhere' style='top: 5px; left: 5px;'>click_me_if_you_dare</a>
</div>
<button type='button' style='top: 380px; width: 120px; right: 10px; height: 20px;' onclick='createFileInput("div_attach");'>new input</button>

the JS code: JS代码:

function createFileInput(parentID) {
  var atop, index;
  var parent = document.getElementById(parentID);
  var control = document.createElement('input');

  control.setAttribute('type', 'file');
  elements = parent.getElementsByTagName('*');

  // debug only ...
  for (index = 0; index < elements.length; ++index) {
    alert(elements[index].style.top);
    alert(elements[index].style.height);
  };

  if (elements.length > 0)
    atop = elements[elements.length - 1].style.top + elements[elements.length - 1].style.height + 5;
  else
    atop = 5;
  control.setAttribute('name', 'FILE_' + elements.length);
  control.className = 'flat'; 
  control.style.left = 5 + 'px'; 
  control.style.top = atop + 5 + 'px'; 
  //  control.style.top = (elements.length * 30) + 5 + 'px'; 
  control.style.width = 500 + 'px'; 

  parent.appendChild(control);
  control.focus();
}

The code: 编码:

atop = elements[elements.length - 1].style.top + elements[elements.length - 1].style.height + 5;

will return something like "5px5" because it's a string to which you append 5 . 将返回类似"5px5"因为这是您在其后附加5的字符串。

Replace it with 替换为

atop = parseInt(elements[elements.length - 1].style.top, 10) + parseInt(elements[elements.length - 1].style.height, 10) + 5;

Make sure those element have a top and height value, or else parseInt() will return NaN . 确保这些元素具有topheight值,否则parseInt()将返回NaN

edit: In the example, the <a> has no height. 编辑:在示例中, <a>没有高度。

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

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