【问题标题】:"menu > li:first-child" as variable for "getBoundingClientRect().left"“menu > li:first-child”作为“getBoundingClientRect().left”的变量
【发布时间】:2016-11-16 16:54:24
【问题描述】:

我有以下层次结构:

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 个孩子?

【问题讨论】:

  • 我遇到了这个,我认为这是我需要的,但仍在测试! "var box = document.getElementById('sdt_menu').getElementsByTagName('li')[2];"

标签: variables css-selectors getboundingclientrect


【解决方案1】:

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

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

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

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

(或者看起来是这样!)

【讨论】:

    猜你喜欢
    • 2014-06-11
    • 2018-01-12
    • 2011-08-17
    • 2014-06-07
    • 1970-01-01
    • 2022-12-27
    • 2013-07-24
    • 1970-01-01
    相关资源
    最近更新 更多