最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Fade out div on scroll - Stack Overflow

programmeradmin1浏览0评论

I am fading out the div #hero-image when my page scrolls. At the moment, the code below uses a nominal value of 1000 to ensure a slow fade, but my #hero-image div is 100% the height of the browser, so I'd like the full opacity transition from 1 to 0 to happen when the user scrolls the 100% height div out of the initial viewport.

Any help much appreciated!

/* Fade #hero-image on scroll */
$(document).ready(function(){
    $(window).scroll(function(){
        $("#hero-image").css("opacity", 1 - $(window).scrollTop() / 1000);
    });
});

I am fading out the div #hero-image when my page scrolls. At the moment, the code below uses a nominal value of 1000 to ensure a slow fade, but my #hero-image div is 100% the height of the browser, so I'd like the full opacity transition from 1 to 0 to happen when the user scrolls the 100% height div out of the initial viewport.

Any help much appreciated!

/* Fade #hero-image on scroll */
$(document).ready(function(){
    $(window).scroll(function(){
        $("#hero-image").css("opacity", 1 - $(window).scrollTop() / 1000);
    });
});
Share asked Dec 4, 2015 at 17:07 dungey_140dungey_140 2,8029 gold badges42 silver badges75 bronze badges 1
  • So why not just replace 1000 with $("#hero-image").heigth() ? – adeneo Commented Dec 4, 2015 at 17:09
Add a ment  | 

1 Answer 1

Reset to default 10

Use the height of the element instead of the generic 1000 value.

Fiddle: http://jsfiddle/e84enbf2/

$(document).ready(function(){
    $(window).scroll(function(){
        $("#hero-image").css("opacity", 1 - $(window).scrollTop() / $('#hero-image').height());
    });
});

If I understand your ment correctly to make the fade out plete after scrolling half the height of the div just divide by 2.

Fiddle: http://jsfiddle/e84enbf2/1/

$(document).ready(function(){
    $(window).scroll(function(){
        $("#hero-image").css("opacity", 1 - $(window).scrollTop() / ($('#hero-image').height() / 2));
    });
});
发布评论

评论列表(0)

  1. 暂无评论