如何在余烬项目中获得元素的顶部偏移量

How to get the top offset of an element in an Ember project?

本文关键字:元素 顶部 偏移量 余烬 项目      更新时间:2023-09-26

我尝试使用JQuery获得元素的偏移位置

Ember.$('section:nth-child(2)').offset().top

但是这段代码返回了错误的值。这个问题来自Ember,它在元素周围添加了一些Div包装器。

我的DOM结构是这样的:

Html > Body > 
    Div[class='ember-view'] > Div[class='ember-view'] > 
        Div[class='Container'] > Div[class='row']
           Section
           Section
           ...

但是这个Ember Div不被计入parentNode。有解决方案吗?

编辑-这是应用在section上的CSS代码:

section {
    position: relative;
    height: 100vh;
}
article, aside, details, figcaption, figure, footer, header, hgroup,     main, menu, nav, section, summary {
    display: block;
}
*, *::before, *::after {
    box-sizing: inherit;
}

和JS代码:

__init : function() {
Ember.$('#expand-btn').click(function(event) {
  event.preventDefault();
  Ember.$('.nav-link').removeClass('active');
  Ember.$('.nav-link:nth-child(2)').addClass('active');
  var elem = Ember.$('.container>#main>section:nth-child(2)')[0];
  //Return 509, not 480
  console.log(elem.getBoundingClientRect().top - elem.scrollTop);
  Ember.$('html, body').animate({scrollTop : Ember.$('section:nth-child(2)').offset().top}, 750);
});
}.on('didInsertElement')

didInsertElement确保代码在DOM加载后执行。

有一个很棒的DOM Element方法叫做getBoundingClientRect,它返回一个对象,该对象包含从viewport的左上角开始的所有偏移量。

Ember.$('section:nth-child(2)')[0].getBoundingClientRect().top

这个结构没有任何内在的东西会改变offset()的值。div默认是无样式的,offset计算相对于文档,而不是父元素。

如果offset改变,这是因为你的样式或因为offset被调用时,页面是在一个不完整的状态(如果说图像还没有完成加载)。

如果你想要一个更精确的答案,请包括一个更完整的例子,最好是你调用Ember.$('section:nth-child(2)').offset().top和样式。

所以我找到了解决方案。与其说这是一个解决方案,不如说是一个伎俩。我必须注意导航栏偏移量,它是56px。所以我减去小数点的高度和偏移量。我想我会联系Materializecss开发人员找到一个更好的方法与他们