Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
397 views
in Technique[技术] by (71.8m points)

javascript - Adjust div height dynamically based on scroll

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...