CSS background blur on scroll

2019-05-04 08:52发布

问题:

I have fixed background image and upon scroll I want the image to go blur. I know how to do blur in css but do it at specific scroll position.

Here is an example: https://medium.com/good-music/f160ba9e6c52

Any thoughts, examples, advice of snippets will be helpful.

Thanks

回答1:

This codepen does exactly what you want. With browser support in mind it uses 2 images though instead of blur:

http://codepen.io/sota0805/pen/pqLcv



回答2:

On your website example ( https://medium.com/good-music/f160ba9e6c52) there is no css "blur" effect.

You can find one normal image: https://d262ilb51hltx0.cloudfront.net/max/1440/1*THFG10B56f4TQOebO1Zd_w.jpeg

And a blurred image: https://d262ilb51hltx0.cloudfront.net/max/1440/gradv/29/81/40/darken/45/blur/20/1*THFG10B56f4TQOebO1Zd_w.jpeg

After superposing those two images, you have to change the opacity of the first one, it's done!



回答3:

I have only mention the how you can get the position with the scrolling.

$('#divscroll').bind('mousewheel', function (e) {
     var toTop = $(window).scrollTop(); 
     //from this you can get the distance from the top 
     //then you can blur the image as you want with relevent to the position of ur image
});

For IE,Opera previous bind will not work, so you need to

 $('#divscroll').bind('DOMMouseScroll', function (e) {
       var toTop = $(window).scrollTop(); 
       //Handle your logic     
   });

Hope this might help. Cheers.!



回答4:

You can blur the element relative to how far you've scrolled.

$(window).scroll(function(e) {

    var distanceScrolled = $(this).scrollTop();

    $('.element').css('-webkit-filter', 'blur('+distanceScrolled/60+'px)');

});

Here I am using scrollTop() to get the amount of pixels the window has scrolled, and then I set the blur on the element to that number divided by 60, which is just an arbitrary number I chose to get the blur I wanted.

If you want to add the blur at a certain point, you can use an element on the DOM and the check it's position relative to the window.

$(window).scroll(function(e) {

    var elOffset = $('.element').scrollTop() - $(window).scrollTop();

    if(elOffset < 450) {
        $(this).addClass('blur');
    }

});

If .element is less than 450px from the top of the window, the class blur will be added to it. Your blur class would look something like this:

.blur {
    -webkit-filter: blur(4px);
}

You'll probably want to use a transition with it. Don't forget the vendor prefixes.