【问题标题】:get child element offset position from grandparent从祖父母获取子元素偏移位置
【发布时间】:2015-08-22 01:28:08
【问题描述】:

我很难弄清楚这一点。我有一个孩子,父母和祖父母的元素。我想知道与祖父母相关的子偏移位置(位置:绝对)但是这是棘手的部分,父必须像手风琴一样处于相对位置,因此当折叠时子元素也会折叠。我不能在没有相对位置的情况下离开父母,否则绝对孩子不会崩溃并留在原地。

我目前可以在 Jquery 中获取相对于父级的子级位置

// simple accordion
$('.accordion').on('click',function(){
  $(this).next().slideToggle();
})
// get child offset
var childPos = $('.child').position();
console.log(childPos.top) // top position from granparent

CSS

.grandparent{
  position:relative;
}
.parent{
  position: relative;
  padding:20px;
}
.child{
 position: absolute
}

HTML

<div class="grandparent">
  <div class="parent">
    <div class="accordion">accordion</div>
    <div class="child">
      child content
    </div>
  </div>
  <div class="parent">
    <div class="accordion">accordion</div>
    <div class="child">
      child content
    </div>
  </div>
  <div class="parent">
    <div class="accordion">accordion</div>
    <div class="child">
      child content
    </div>
  </div>
</div>

请帮忙!

【问题讨论】:

    标签: javascript jquery html css


    【解决方案1】:

    如果我理解正确,您应该能够重复您的策略,以针对祖父母中的父母的位置。

    var childPos = $('.child').position();
    console.log(childPos.top) // top position of child from parent
    var parentPos = $('.parent').position();
    console.log(parentPos.top) // top position of parent from grandparent
    var childGrandparentPosTop = childPos.top + parentPos.top;
    console.log(childGrandparentPosTop); // top position of child from grandparent
    

    【讨论】:

    • 您可以投票并标记为答案吗?那会帮助我。谢谢。
    猜你喜欢
    • 2012-06-13
    • 2013-12-30
    • 2012-07-23
    • 1970-01-01
    • 1970-01-01
    • 2015-08-30
    • 1970-01-01
    • 2013-03-07
    • 1970-01-01
    相关资源
    最近更新 更多