【问题标题】:jQuery - Loop through parent div, get bottom position of last child divjQuery - 遍历父 div,获取最后一个子 div 的底部位置
【发布时间】:2015-08-30 04:24:03
【问题描述】:

我正在尝试遍历父 div 并获取最后一个子 div 的底部位置。

<main id="swipe-page">
    <div class="dragend-page">
        <div class="page-content"></div>
        <div class="page-content"></div>
        <div class="page-content"></div>
    </div>
    <div class="dragend-page">
        <div class="page-content"></div>
        <div class="page-content"></div>
    </div>
    <div class="dragend-page">
        <div class="page-content"></div>
        <div class="page-content"></div>
        <div class="page-content"></div>
        <div class="page-content"></div>
        <div class="page-content"></div>
    </div>
</main>

最后一个页面内容 div 的底部位置将被设置为父拖动页面 div 的总高度。我该怎么做?

$.each($('.dragend-page'), function(i, dragend_page) {
    $('.page-content', dragend_page).each(function() {
         var p = this.position();
         console.log(p.bottom);
     });
})

这将获得所有子 div 的底部位置 - 而不仅仅是最后一个。并且位置函数一定是不正确的,因为它返回“this.position is not a function”

【问题讨论】:

  • 尝试 .page-content:last 作为选择器。然后你也不需要 each 调用。 Position 是正确的函数,但在每个函数内部你需要做 $(this) 因为它是一个 jQuery 函数而不是一个 Dom 函数。
  • 而 this.position() 应该是 $(this).position()

标签: javascript jquery html css


【解决方案1】:

正如@Rudi 在 cmets https://api.jquery.com/position/ 中提到的那样,返回一个包含属性 top 和 left 的对象 .. 所以你可以使用它

$('.dragend-page').each(function(i, dragend_page) {
    var lastDiv = $(this).find('.page-content:last-child');
    var bottomPosition = lastDiv.position().top +  lastDiv.outerHeight(true);
    console.log(bottomPosition );

})

此代码将输出每个 .dragend-page 中最后一个 .page-content 的底部位置

【讨论】:

  • api.jquery.com/position 返回一个包含 top 和 left 属性的对象。
  • @Rudi 谢谢.. 我更新了我的答案
  • 感谢@Mohamed-Yousef。然后我添加 $(this).height(p);更改父高度,但当我移至下一张幻灯片时它没有改变。 $("#swipe-page").dragend({ afterInitialize: function() { this.container.style.visibility = "visible"; }, onSwipeEnd: function() { var next_slide = parseInt(this.page) + 1 ; window.location.hash = "slide="+next_slide; $('.dragend-page').each(function(i, dragend_page) { var lastDiv = $(this).find('.page-content:last -child'); var p = lastDiv .position().top + lastDiv.outerHeight(true); $(this).height(p); }) } });
  • @steeped 我认为您需要运行该代码两次 .. 一次在 onSwipeEnd 和一次在 $(document).ready() 之后 .. 我的意思是尝试在 .dragend({
【解决方案2】:

this 将为您提供最后一个 div 的位置,而无需遍历 div

$(function(){
    console.log($(".dragend-page :last-child").last().position());
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 2012-06-06
    • 1970-01-01
    • 1970-01-01
    • 2012-07-22
    • 2012-02-03
    相关资源
    最近更新 更多