How to fade in/out div when scrolling past certain points on a page?

删除回忆录丶 提交于 2019-12-14 03:43:16

问题


How would you fade/in out divs that are ontop of each other, when the user scrolls to a certain point in the page? I have a fixed button that I want to change when the user reaches 6 different points on the page. In other words so that I can link to 6 different things from the same button at different points in the page say 1000px from the top, then 2000px and so on.

Each of the buttons have different words in them so I just want each button to fade in after the next when the correct number of px is reached when scrolling.

html

<div class="buttonOne">button one</div> <div class="buttonTwo">button two</div> <div class="buttonThree">button three</div>

css

.buttonOne, .buttonTwo, .buttonThree { position: fixed; margin-top: 3em; }

All positioned fixed and on top of each other. Each one should fade in at 100px, 200px, 300px and so on?


回答1:


Use jquery:

$(window).scroll(function(){
if($(window).scrollTop() === 10){
   $('.element').fadeOut();
}
});

Fiddle: http://jsfiddle.net/Hive7/vV7Wd/2/

To add more use:

if ($(window).scrollTop() >= "number of pixels") {
        if ($('"button plus number"').css('display') === 'none') {
            $('"button plus number"').fadeIn('slow');
            $('"button plus number"').prev().fadeOut();
            $('"button plus number"').next().fadeOut();
        }
    }

Elements in double quotes are up to you to set

Example (for number 4):

if ($(window).scrollTop() >= 400) {
            if ($('button4').css('display') === 'none') {
                $('button4').fadeIn('slow');
                $('button4').prev().fadeOut();
                $('button4').next().fadeOut();
            }
        }

Or use a for loop:

$(window).scroll(function () {
    for (i = 0; i <= 20; i++) {
        if ($(window).scrollTop() >= (i * 100)) {
            if ($(window).scrollTop() <= ((i * 100) + 100)) {
                $('.button' + i).fadeIn('slow');
                $('.button' + i).prev().fadeOut();
                $('.button' + i).next().fadeOut();
            }
        }
    }
});

The for loop is better as it means that you only have to implement one thing everytime you add one which is the condition in the for loop



来源:https://stackoverflow.com/questions/17722245/how-to-fade-in-out-div-when-scrolling-past-certain-points-on-a-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!