javascript - jQuery 使用 height() 来改变 div 的高度

标签 javascript jquery css animation css-animations

尝试获取在动画中发生变化的 div 的高度。获得该高度后,我需要在文本 h4 标签中将其显示为百分比。

目前动画由 CSS 和 jQuery 控制。问题是,当我使用 height() 时,它只返回 div 的第一个高度,并且不会在 div 高度变化时显示它。我想我需要以某种方式遍历高度,但我不确定该怎么做。我已将其设置为在当前高度上显示 console.log。

HTML

<div id="brain">
    <div id="brain-image"></div>
    <div id="circle-percent">
        <p class="retention-title">Memory Retention</p>
        <h4 class="brain-percentage">20%</h4>
    </div>
    <div class="water"></div>
</div>

CSS

#brain {
background: #f5f5f5; 
-webkit-border-radius: 0px;
-moz-border-radius: 0px;
border-radius: 0px;
width: 713px;
height: 608px;
position: relative;
z-index: 90;
margin-left: 120px;
}
.water {
background-color: #5bbd97;   
background-position: top right;
position: absolute;
bottom: 0px;
width: 713px;
height: 608px;
-webkit-transition: all 10s ease-out;
-moz-transition: all 10s ease-out;
-o-transition: all 10s ease-out;
transition: all 10s ease-out;
-webkit-border-radius: 0px;
-moz-border-radius: 0px;
border-radius: 0px;
}
#brain-image {
background: url('img/brain.png');
width: 713px;
height: 608px;
display:block;
z-index: 99;
position:absolute;
top:0
}

JavaScript

 // *** Animation based on scroll ***

 jQuery(document).ready(function ($) {
      jQuery(window).scroll(function() {
                    if (jQuery(window).scrollTop() > 600) {
                    jQuery('.water').css('height','80px');
      }
 });

 // ** Getting the height here **

 jQuery('.water').height(function() {
           var currentWidth = $('.water').height();
           console.log(currentWidth);
       });

  });

最佳答案

我提出的解决方案使用 jQuery 的 Animate和 Step 函数,而不是严格的 CSS 转换。当 Window Scroll Event 被触发,并且你离顶部有一定距离时,触发 resize 函数。这个函数接受一个 jQuery 元素和一个在 fiddle 中显示的初始高度。当动画开始时,在每一步中,输出显示为初始高度的百分比。

https://jsfiddle.net/ko9s44pn/

function resize( el, height )
{
  if (height != 80)
  {
    el.animate({ height: 80 },{ duration: 5000,
      step: function( curheight )
      {
        $('#output').text((curheight / height) * 100 + '%');
      }
    });
  }
}

在 animate 中使用 step 函数就是你提到的你正在寻找的迭代。这使您可以在给定的动画间隔内执行某些操作。这不是一个完美的解决方案,但希望它能为您指明正确的方向!

关于javascript - jQuery 使用 height() 来改变 div 的高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30514406/

相关文章:

javascript - 输入标签中的多种字体颜色

javascript - 获取开始日期和结束日期之间的日期数组

javascript - 循环 2 同步幻灯片,幻灯片循环之间有延迟

javascript - 只有 Internet Explorer 给出错误 : 'document.getElementById(...)' is null or not an object

javascript - 如何使 html 中的单选框看起来像复选框并在选中时使它们具有 x ?

javascript - Canvas 图像调整大小/scew/dnd

javascript - 删除ajax内的对象

javascript - 作为参数给出时返回 ID 元素

html - 如何垂直放置条形图的条形,使它们都位于容器的底部?

html -::after 和::before 伪类阻塞 anchor 标签