Calculate div's position within a div

馋奶兔 提交于 2019-12-11 21:06:18

问题


Good day, I need some help in JS please.
Say I have this HTML:

<div>
    <div onclick="countPos()"></div>
    <div onclick="countPos()"></div>
    <div onclick="countPos()"></div>
</div>

When I click on a div (inside the parent's div), I want a JS function to fire off, which will return the position of that div. So, if I click the third div - return 3, if I click the first div - return 1 and so on. How can I do that please?


回答1:


You need to send the current clicked element to the function like

<div onclick="countPos(this)"></div> 

Then in the function you can create an array of the elements inside the parent then find the index.

function countPos(elem){
  var nodeList = Array.prototype.slice.call( elem.parentNode.children );
  var index = nodeList.indexOf( elem ) + 1;
  // do your stuff with index
}

FIDDLE




回答2:


I would suggest giving each div an id, and passing that value to the JS function. Something like...

<div>
   <div id="div1" onclick="countPos(this.id)"></div>
   <div id="div2" onclick="countPos(this.id)"></div>
   <div id="div3" onclick="countPos(this.id)"></div>
</div>


来源:https://stackoverflow.com/questions/23239203/calculate-divs-position-within-a-div

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!