jquery实时监听div高度变化

$(".btn1").click(function(){
$("#box").animate({height:"300px"});
});

我想实时的监听$("#box")的高度,请问该如何操作呢?

阅读 27.6k
6 个回答

解释一下什么叫实时的监听?

根据回复补充:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <script src="jquery.min.js"></script>
  <style>
    #box{
      height: 100px;
      width: 100px;
      background: red;
    }
  </style>
</head>
<body>
  <div id="box"></div>
  <button class="btn1">dianwo</button>
  <script>
    $(".btn1").click(function(){
      $("#box").animate({height:"300px"}, {step: function(){console.log($(this).height())}}).resize(function() {
        console.log($(this).height());
      });
    });
  </script>
</body>
</html>

这样呢?

$("#box").resize(function() {
    console.log($(this).height());
});
$("#box").bind(,function(){
alert($(this).css.height);
});

建议你把js和css区分开,js只起控制作用,不处理样式。

$(".btn1").click(function(){
    $("#box").animate({height:"300px"}); 
});

改成

js:
$('.btn1').click(function(){
    $('#box').addClass('open');
});
$('#box').on('animationiteration', function(){
    console.log($(this).height());
});

css:
@keyframes slidedown {
    from {
        height: 0;
        // 让元素显示出来的代码
    }

    to {
        height: 300px;
    }
}
.open {
    animation: slidedown 0.3s ease-in-out;
}

当然我写得不完整,可能都不会生效,我只是推荐你向这个方向写。这个方向是肯定行得通的。

jQuery貌似没有实时监听DOM元素变化的方法,推荐使用:HTML5的新特性:Mutation Observer
参考文档

已经有了animate console.log打印高度 为什么还要加resize 这个我删了没影响啊

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题