计算div在div中的位置 [英] Calculate div's position within a div
本文介绍了计算div在div中的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
美好的一天,我需要一些 JS 方面的帮助.
假设我有这个 HTML:
<div onclick="countPos()"></div><div onclick="countPos()"></div><div onclick="countPos()"></div>
当我单击一个 div(在父级的 div 内)时,我希望触发一个 JS 函数,该函数将返回该 div 的位置.因此,如果我单击第三个 div - 返回 3,如果我单击第一个 div - 返回 1,依此类推.请问我该怎么做?
解决方案
你需要将当前点击的元素发送到函数如
<div onclick="countPos(this)"></div>
然后在函数中,您可以创建父元素内部元素的array
,然后找到索引.
function countPos(elem){var nodeList = Array.prototype.slice.call( elem.parentNode.children );var index = nodeList.indexOf( elem ) + 1;//用索引做你的事情}
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?
解决方案
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
}
这篇关于计算div在div中的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文