简体   繁体   English

向下滚动动画并向上滚动

[英]Animate on scroll down and scroll up

I am trying to animate a group of buttons from a relative position to a fixed position on each scroll by. 我正在尝试使每个滚动中的一组按钮从相对位置动画到固定位置。

HTML HTML

<div class="menu">
    <button class="button"></button>
    <button class="button"></button>
</div>

CSS CSS

.button {
    display: inline-block;
    position: relative;
    margin: 3px;
    height: 56px;
    width: 56px;

    -webkit-transition: all 0.5s ease;
    -moz-transition: all 0.5s ease;
    -o-transition: all 0.5s ease;
    transition: all 0.5s ease;
}

.grouped {
    z-index: 1000;
    position: fixed;
    top: 31px;
    right: 20px;
}

JS JS

var scrollFlag = false;

$(window).scroll(function() {
    var menu = $(".menu"),
        scrollTop = window.scrollTop;

    if(menu.offset().top <= (scrollTop + 50)) {
        if(scrollFlag == false) {
            $(".menu button").each(function() {
                var button = $(this);

                button.addClass("grouped");
            });

            scrollFlag = true;
        }
    } else {
        $("#intro div.menu button").each(function() {
            $(this).removeClass("grouped");
        });

        scrollFlag = false;
    }
});

As it is now the buttons just jump to the fixed position. 现在,按钮只是跳到固定位置。 I realise this is because they do not have set top/right values for the animation to begin from. 我意识到这是因为它们没有设置动画的上/下值。

I tried to overcome this by getting the buttons offsets and setting them as the top and left values but this didn't seem to work either. 我试图通过获取按钮偏移并将它们设置为顶部和左侧的值来克服此问题,但这似乎也不起作用。

Any ideas? 有任何想法吗?

What about JQuery's .animate() function? JQuery的.animate()函数呢?

You can do something like: 您可以执行以下操作:

$("#myButton").animate({         
    //this value would either be how far you want it to move, 
    //or the final position; I'm not sure which.
    top: 50px; 
    left: 50px;
}, 500); //the number here is the time in ms for the animation to play.

I don't think its good idea but anyway 我不认为这是个好主意,但无论如何

$(window).scroll(function() {
    var menu = $(".menu"),
        scrollTop = $(window).scrollTop();
    if($('.button:nth-child(1)').css('position') !== 'fixed'){
        if(menu.offset().top <= (scrollTop + 50)) {
            $(".menu button").each(function() {
                var button = $(this);

                button.addClass("grouped");
            });
        }
    } else {
        if(scrollTop  <= 31){
            $("div.menu button").each(function() {
                $(this).removeClass("grouped");
            });
        }
    }
});

JSFIDDLE 的jsfiddle

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

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