根据滚动位置,使用动画更改类 [英] Changing classes with animation depending on scroll position

查看:129
本文介绍了根据滚动位置,使用动画更改类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的页面包含四个部分,每个部分设置为100%高度,具有不同的背景颜色。在顶部我有一个固定的菜单。我想让菜单根据用户当前的部分更改背景颜色,因此它与背景更好地混合。

My page contains four sections, each set to 100% height with different background color. At the very top I have a fixed menu. I want the menu to change it's background color depending on which section the user is at the moment, so it blends better with the background.

到目前为止,我已经设法菜单的bg颜色更改投资组合时,但它不是很多,我被卡住。它必须再次改变它的颜色,当用户滚动回到家,到大约等等。此外,我想它的动画,但我不知道如何使用animate()与addClass()。我一直在尝试过去两天没有成功。

So far I have managed to make the menu's bg color to change when portfolio is entered, but it's not much and I am stuck. It has to change it's color again, when the user scrolls back to home, forth to about and so on. Also, I want it to be animated, but I don't know how to use animate() with addClass(). I've been trying for the past two days with no success at all.

另一件让我折服的是菜单元素也应该响应滚动位置。例如,如果用户从主页滚动到投资组合,则活动类应应用于投资组合并从主页中移除。希望你有这个想法。

The other thing that tortures me is that the menu elements should respond to the scroll position too. For example, if the user scrolls from Home to Portfolio, the active class should be applied to Portfolio and removed from Home. Hope you got the idea.

到目前为止,我的代码看起来像这样:

So far my code looks like this:

<div class="menu">
    <div id="menu-center">
        <ul>
            <li><a class="active" href="#home">Home</a></li>
            <li><a class="inactive" href="#portfolio">Portfolio</a></li>
            <li><a class="inactive" href="#about">About</a></li>
            <li><a class="inactive" href="#contact">Contact</a></li>
        </ul>
    </div>
    </div>
    <div id="home"></div>
    <div id="portfolio"></div>
    <div id="about"></div>
    <div id="contact"></div>

我不知道为什么,但是我不能在不打破整个帖子的情况下,因此只需转到 jsFiddle 即可一起查看。

I have no idea why, but I can't post the css here without breaking the whole post, so just go to jsFiddle to see it all together.

$(document).ready(function () {
    var menu = $('.menu');
    var portfolio_position = $('#portfolio').offset().top;
    var about_position = $('#about').offset().top;
    var contact_position = $('#contact').offset().top;

    $(window).scroll(function () {
        var scroll = $(this).scrollTop();
        if (scroll >= portfolio_position) {
            menu.removeClass('menu').addClass('menu-light');
        }
    });
});


推荐答案

请参阅: http://jsfiddle.net/Dxtyu/1/

var menu = $('.m1');

$(window).scroll(function () {
    var y = $(this).scrollTop();
    var z = $('#portfolio').offset().top;

    if (y >= z) {
        menu.removeClass('menu').addClass('light-menu');
    }
    else{
        menu.removeClass('light-menu').addClass('menu');
    }
});

这篇关于根据滚动位置,使用动画更改类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆