【问题标题】:Using jQuery each() function to calculate heights of divs使用 jQuery each() 函数计算 div 的高度
【发布时间】:2014-12-09 02:52:50
【问题描述】:

目前我正在使用一个函数来计算元素内某些 div 的高度,以强制执行一个名为“DotDotDot”的 jquery 插件。这对于单个 div 来说绝对完美。但是我想要实现的是一系列 div 执行此操作,但目前在使用 .each() 函数时它对我不起作用,并且当它到达第二个 div 时它会中断。希望对此有任何帮助,而不是 jQuery 中最好的 - 下面的小提琴。

TL;DR

  • 使用名为 DotDotDot 的 jquery 插件计算容器内 div 的高度以省略文本。
  • 使用 .each() 函数复制多个 div。
  • 不工作。

JS Fiddle

DotDotDot Plugin

$(document).ready(function () {

$("#desc").each(function () {

    var imgheight = $(".image").height();
    var h2height = $("#desc h2").height();

    $("#desc").height(670 - imgheight - h2height - 30);

    $("#desc").dotdotdot({
        after: "a.readmore"
    });
});

});

【问题讨论】:

  • 您应该包含一段标记的摘录。 div 是否共享一个类?
  • 如所写,你的 .each() 是没有意义的——它会循环 $('#desc') 的结果,它只能是一个元素(或者没有,如果它不存在)。也许你想让'#desc *' 循环播放所有#desc 的孩子?

标签: javascript jquery html each


【解决方案1】:

首先,ID 属性在 DOM 中应该是唯一的。你不能有两次#desc,所以我把它们改成了class。

我已经更新了你的 jsfiddle:http://jsfiddle.net/dLp38687/7/

jQuery: 每次通过选择示例类来循环遍历父 div。在每次迭代中,您使用 $(this).find(CHILD) 选择当前示例 div 的子级。

$(document).ready(function () {

    $(".example").each(function () {

        var imgheight = $(this).find(".image").height();
        var h2height = $(this).find(".desc h2").height();

        $(this).find(".desc").height(670 - imgheight - h2height - 30);

        $(this).find(".desc").dotdotdot({
            after: "a.readmore"
        });
    });

});

更新后的标记(略删)

<div class="container">
    <div class="example">
        <div class="image">
            <img src="http://a1.dspnimg.com/data/l/9ac8f53d4b3ec8d77865fd1b542a7b1f_xRgXa9UV_l.jpg" />
        </div>
        <div class="desc">
             <h2>This is a title of a post and it can span 2 lines</h2>

            <p>Lorem Ipsum isike Aldus PageMaker including versions of Lorem Ipsum.</p>
        </div>
    </div>
    <div class="example">
        <div class="image">
            <img src="http://a1.dspnimg.com/data/l/3156205047987_i80wZOig_l.jpg" />
        </div>
        <div class="desc">
             <h2>This is a title of a post and it can span 2 lines</h2>

            <p>Lorem Ipsum is set sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
        </div>
    </div>
</div>

【讨论】:

    猜你喜欢
    • 2012-07-18
    • 1970-01-01
    • 2014-03-25
    • 2010-12-21
    • 2013-01-13
    • 1970-01-01
    • 1970-01-01
    • 2015-09-24
    • 2021-04-12
    相关资源
    最近更新 更多