简体   繁体   English

如何使用jQuery滚动来更改元素的高度?

[英]How to use jQuery scroll to change the height of an element?

I have a HTML class navigation with the initial height of 100px and min-height is 40px . 我有一个HTML类导航 ,其初始高度为100px最小高度40px I want to change the height of the class, based on the scroll (if scroll down than size will decrease and if scroll up than size will increase). 我想根据滚动来更改类的高度(如果向下滚动的大小会减小,而向上滚动的大小会增大)。 I use the following code and it's working perfectly. 我使用以下代码,并且运行良好。

$(window).scroll( function() {
    if( $('.navigation').offset().top > 50 )
    {
        $('.navigation').css({
           'height' : '40px',
           'background' : 'rgba(37, 37, 37, 0.9)'
        });
    } else {
       $('.navigation').css({
         'height' : '100px',
         'background' : '#b24926'
       });
    }
});  

If I press the keyboard down arrow key two times than navigation class moved from original height to minimum height and if the up arrow key press two times than navigation class moved from minimum height to original height. 如果我按下键盘的向下箭头键两次,则导航类别从原始高度移至最小高度;如果我按下向上的箭头键两次, 导航类别从最小高度移至原始高度。
But I want to make the scroll more smooth (like 4-5 up or down key presses to reach from one height to another). 但是我想使滚动更平滑(例如4-5向上或向下按键可以从一个高度到达另一个高度)。

For example: initial height is: 100px and minimum height is 30px. 例如:初始高度为:100像素,最小高度为30像素。 Now: if down arrow key is pressed/mouse wheel is move down one time than height will be 85px, if again down arrow is pressed height will be 70px and so on. 现在:如果按下向下箭头键/鼠标滚轮向下移动一次,则高度将为85px,如果再次按下向下箭头,则高度将为70px,依此类推。 That means for each down arrow key is pressed/mouse wheel is move down than height will decrease by 15-20px and for each up arrow key is pressed/mouse wheel is move up, height will increase by 15-20px. 这意味着,每按一次向下箭头键/鼠标滚轮向下移动,高度就会降低15-20px;对于每按一次向上箭头键/鼠标滚轮向上移动,高度会增长15-20px。

Can anyone tell me how can I do that (without using third party api). 谁能告诉我该怎么做(不使用第三方api)。

  • Thanks 谢谢

You can use simple percent calculation to update height 您可以使用简单的百分比计算来更新身高

var limitForMinimalHeight = 400; //after this distance navigation will be minimal height
var maxHeight = 100;
var minHeight = 40;
$(window).scroll( function() {
    var screenTop = $(document).scrollTop();
    var achievedDistancePercent =  Math.min(screenTop*100/limitForMinimalHeight, 100);
    var amounToAdd = ((maxHeight - minHeight) * (100 - achievedDistancePercent))/100;
    var newHeight = minHeight + amounToAdd;
    $('.navigation').height(newHeight);        
});

You can test it on JSFiddle 您可以在JSFiddle对其进行测试

           $(document).scroll(function() {
                if($(this).scrollTop()>100) {
                    $('.selector').addClass('scrolled');
                }
                if($(this).scrollTop()<40) {
                    $('.selector').removeClass('scrolled');
                }
            });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM