如何在标题中添加css转换到js滚动

How to add css transitions to js scroll in header?

本文关键字:转换 js 滚动 css 添加 标题      更新时间:2023-09-26

我有一个页眉,当页面向下滚动时会出现。我试图添加css转换以使其淡入淡出,因为我读到使用javascript进行淡入淡出的效率不高。

.header-wrapper {
    top:0;
    left:0;
    right:0;
    position: fixed;
    display:none;
    height: 60px;
    border-top: 1px solid #000;
    background: red;
    z-index: 1;
}
.header-wrapper.active {
     display:block;   
}
.header {
    background-color:#000;
    height:80px;
}

这是js小提琴

$(window).scroll(function () {
    var y = $(window).scrollTop();
    // if above 300 and doesn't have active class yet
    if (y > 300 && !$('.header-wrapper').hasClass('active')) {
        $('.header-wrapper').addClass('active');
    // if below 300 has still has active class
    } else if(y <= 300 && $('.header-wrapper').hasClass('active')) {
        $('.header-wrapper').removeClass('active');
    }
    });

使用css3属性transition添加转换。

造成混淆的一个常见原因是:只能转换接受数值的属性。因此,您无法在display: blockdisplay: none之间转换。

但是,可以使用在opacity: 0opacity: 1之间转换

transition: 0.5s opacity

看起来像这样:

.bottomMenu {
    ...
    opacity: 0;
    transition: 0.5s opacity;
    ...
}
.bottomMenu.active {
     opacity: 1;   
}

对于您的特定情况,我可能建议在060px之间转换高度。

为此,您可以使用:

transition: 0.5s height

因此:

.bottomMenu {
    ...
    height: 0;
    transition: 0.5s height;
    ...
}
.bottomMenu.active {
     height: 80px;   
}

要设置不透明度的动画,元素必须可见。因此,移除display:none并使其完全透明(opacity:0)。然后,当类名更改时,您可以使用CSS转换来为opacity设置动画:

.bottomMenu {
    ...
    display:block;
    opacity: 0;
    transition: opacity .25s ease-in-out;
    -moz-transition: opacity .25s ease-in-out;
    -webkit-transition: opacity .25s ease-in-out;
}
.bottomMenu.active {
     opacity:1   
}

http://jsfiddle.net/oL9ro4gL/6/

此外,您不局限于仅设置不透明度的动画:

.bottomMenu {
    ...
   transition: all .25s ease-in-out;
}
.bottomMenu.active {
    opacity:1;
    height: 60px;
    background-color: blue;
    transform:rotate(180deg);
    color:white;
    font-size:40px;
    etc...
}

http://jsfiddle.net/oL9ro4gL/8/

很遗憾,您无法设置display属性的动画。请参阅此问题及其解决方法建议。