根据滚动动态调整div高度 [英] Adjust div height dynamically based on scroll

查看:139
本文介绍了根据滚动动态调整div高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这样做很简单,但我似乎无法在搜索中找到任何内容。

到达页面上的某个滚动位置,然后将div设置为不同大小的动画,但是我想根据滚动位置调整div的最大高度。最初我希望div max-height大约为150px,然后当您从页面上200px左右滚动到页面下方400px时,我希望div的最大高度降低到75px。显然,当您向后滚动时,它会变大。



我无法提供我已经尝试过的示例,因为我尚未尝试它因为我不知道从哪里开始。



注意:尺寸应随滚动位置逐渐调整。

解决方案

我不知道我是否理解你的问题,但是当我做到这一点时:D


$ (scrollTop< b $ b

  $(window).scroll(function(){
var scrollTop = $(window).scrollTop();
; 200){
maxHeight = 150;
} else if(scrollTop> 400){
maxHeight = 75;
} else {
maxHeight = 150 - 75 *(((scrollTop-200)* 100)/ 200)/ 100;
}
$('#thediv')。stop()。animate({'max-height':maxHeight +px },500);
})

这里有一个例子: https://jsfiddle.net/keccs4na/


I know there's a pretty simple way of doing this, but I can't seem to find anything in my searches.

I've found lots of examples of getting to a certain scroll location on the page and then animating a div to a different size, however I want to adjust a div's max height depending on the scroll location. Initially i'd like the div max-height to be about 150px, and then as you scroll from around 200px down the page to 400px down the page, I want the max-height of the div to decrease to 75px. Then obviously as you scroll back up, it gets larger.

I can't provide an example of what I've tried already, as I'm yet to attempt it as I have no idea on where to start.

Note: The size should gradually adjust with the scroll position.

解决方案

I'm not sure if I understood your problem, but when I did I came out with this :D

$(window).scroll(function(){
  var scrollTop = $(window).scrollTop();
  if(scrollTop < 200){
    maxHeight = 150;
  }else if(scrollTop > 400){
    maxHeight = 75;
  }else{
    maxHeight = 150 - 75 * (((scrollTop-200) * 100)/200)/100;
  }
  $('#thediv').stop().animate({'max-height': maxHeight+"px"}, 500);
})

Here you have a sample : https://jsfiddle.net/keccs4na/

这篇关于根据滚动动态调整div高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆