【问题标题】:How to get div height after add jquery append without using css overflow添加jquery append后如何在不使用css溢出的情况下获取div高度
【发布时间】:2017-05-07 22:26:02
【问题描述】:

我想在最后添加一些元素后获得 div 高度,而不使用 css 溢出。

HTML 代码:

<div id="wall"></div>

Javacript 代码:

var walldown = setInterval(walldownfn, 10000);

    function walldownfn() {

        $.post("/php/post.php", function(data, status){
          $("#wall").append(data+"<br>");

        });
        var awrap = document.getElementById("wall");
        alert(awrap);
        }

警报输出:

[object HTMLDivElement] or 0 height

ajax 响应数据是 HTML 代码。

例子:

<div class="card" style="width: 20rem;">
  <img class="card-img-top" src="..." alt="Card image cap">
  <div class="card-block">
    <h4 class="card-title">Card title</h4>
    <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
    <a href="#" class="btn btn-primary">Go somewhere</a>
  </div>
</div>

【问题讨论】:

  • 你试过$("#wall").height()吗?
  • 是的,但这也总是得到 0 高度
  • 追加内容后,需要在函数内部调用。

标签: javascript jquery html


【解决方案1】:

试试这个:

var walldown = setInterval(walldownfn, 10000);

function walldownfn() {
    $.post("/php/post.php", function(data, status){
        $("#wall").append(data+"<br>");
        alert($("#wall").height());
    });
}

【讨论】:

    【解决方案2】:

    通过使用$("#wall").height(),您可以获得每次延时的 div 高度参见下面的代码(控制台而不是警报)

    var walldown = setInterval(walldownfn, 1500);
    
    var returned_data = '<div class="card" style="width: 20rem;"><img class="card-img-top" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSQythd0ly14qbZd7YEJ9WreTX4-dBQw7vfGS33ZXbTQRJjE1AHITKZE5g" alt="Card image cap"><div class="card-block"><h4 class="card-title">Card title</h4><p class="card-text">Some quick example text to build on the card title and make up the bulk of the card\'s content.</p><a href="#" class="btn btn-primary">Go somewhere</a></div></div>';
    function walldownfn() {
    
      $.post("https://httpbin.org/post", {text:returned_data},function(data, status){
          $("#wall").append(data.form.text);
          console.log("height : "+$("#wall").height());
      });
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="wall"></div>

    【讨论】:

    • 这在使用 ajax 时不起作用。我的主要目的是使用 ajax 很抱歉不知情。使用 br 时只获取新的行高。
    • @ind 这不是问题中提到的,请重新表述你的问题,你的意思是使用 ajax 吗?您使用 ajax 获取信息,然后将其呈现在该 div 中?
    • 你是正确的,在 ajax 将数据渲染到 div 之后,我想要那个 div 高度。我总是在不使用 br 的情况下得到 0。如果我使用 br,它的断线高度只有大约 12px,不包含高度
    • 给我一个你返回数据的例子?
    • 如果你不让你的 div css word-wrap:break-word; 它总是返回相同的高度,因为输出数据是在 inline 中设置的
    猜你喜欢
    • 2019-04-27
    • 1970-01-01
    • 1970-01-01
    • 2016-12-29
    • 2011-03-15
    • 1970-01-01
    • 1970-01-01
    • 2013-05-01
    • 1970-01-01
    相关资源
    最近更新 更多