【问题标题】:Animate on scroll down and scroll up向下滚动和向上滚动时动画
【发布时间】:2015-07-17 04:41:53
【问题描述】:

我正在尝试将一组按钮从相对位置设置为每次滚动时的固定位置。

HTML

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

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

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;
    }
});

现在按钮只是跳到固定位置。我意识到这是因为他们没有设置动画开始的顶部/右侧值。

我试图通过获取按钮偏移量并将它们设置为顶部和左侧值来克服这个问题,但这似乎也不起作用。

有什么想法吗?

【问题讨论】:

  • 您想用 2 个按钮固定菜单 .. 还是固定每个按钮?? ..如果您固定每个按钮,固定位置将使它们相互重叠
  • 是的,这就是我想要的,让它们相互重叠。效果就像一堆东西都聚集在一起。我打算有第二个功能,它打开一个菜单,里面都有它们。它只是让它们从页面中的任何位置访问的一种很酷的方式。

标签: jquery html css jquery-animate css-animations


【解决方案1】:

我不认为这是个好主意,但无论如何

$(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

【讨论】:

  • 谢谢,你看的是动画吗?它只是像我的代码一样为我跳跃。
【解决方案2】:

JQuery 的.animate() 函数呢?

你可以这样做:

$("#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.

【讨论】:

  • 感谢您的回答。我相信您希望它移动多少。但这又是相对于容器而言的……我想,所以它会产生与我的代码相同的效果。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-10
  • 2017-04-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多