1

我有以下层次结构:

menu > li:first-child
menu > li:nth-child(2)
menu > li:nth-child(3)
menu > li:nth-child(4)
menu > li:nth-child(5)
menu > li:nth-child(6)
menu > li:nth-child(7)
menu > li:nth-child(8)
menu > li:nth-child(9)

我试图将这些中的每一个放入一个变量中,以便:

var fromleft = box.getBoundingClientRect().left;
var fromtop = box.getBoundingClientRect().top;

它现在适用于:

var box = document.getElementById('menu');
var fromleft = box.getBoundingClientRect().left;
var fromtop = box.getBoundingClientRect().top;

但不是:

var box = document.getElementById('menu > li:first-child');
var fromleft = box.getBoundingClientRect().left;
var fromtop = box.getBoundingClientRect().top;

为了在变量中使用第一个孩子或第 n 个孩子,我需要做什么?

4

1 回答 1

0

我遇到了这个,我认为这是我需要的!

var box = document.getElementById( 'sdt_menu' ).getElementsByTagName( 'li' )[0];" 

并且... 0 = 第一个孩子,1 = 第 n 个孩子(2),等等

另外... 'li' 可以更改为 'div' 等。

(或者看起来是这样!)

于 2016-11-16T20:22:51.710 回答