(CSS) Make a background image scroll slower than everything else

后端 未结 8 1094
死守一世寂寞
死守一世寂寞 2020-12-12 17:33

here is is my CSS code for the body:

body {
  padding: 0;
  margin: 0;
  background-image: url(\"../images/background.jpg\");
  background-repeat: no-repeat;         


        
8条回答
  •  南笙
    南笙 (楼主)
    2020-12-12 17:43

    Agree that it isn't possible just with css, because you have to compute image and document height ratio. I also like this effect, that's why created simple function that does just that. Here is function and its call on scroll event:

    $(window).on('scroll', function() {
    	smoothBackgroundScroll("relative/image/url");
    });
    
    function smoothBackgroundScroll(imgsrc) {
    	function loadImageHeight(url, width) {
    		var img = new Image();
    		img.src = url;
    		if (width) {
    			img.width = width;
    		}
    		return img.height;
    	}
    
    	var dh, wh, ih, st, posy, backh, backw;
    	if (!this._smoothBackgroundScroll) {
    		var bcksize = $(document.body).css('background-size');
    		var bmatch = /(\w+)\s*(\w+)/.exec(bcksize);
    		if (!bmatch || bmatch.length < 3) {
    			backh = loadImageHeight(imgsrc)
    		} else {
    			backh = parseInt(bmatch[2]);
    			if (isNaN(backh)) {
    				backw = parseInt(bmatch[1]);
    				backh = loadImageHeight(imgsrc, parseInt(backw));
    			}
    		}
    		this._smoothBackgroundScroll = {
    			dh: $(document).height()
    			, wh: $(window).height()
    			, ih: backh
    		}
    	}
    	dh = this._smoothBackgroundScroll.dh;
    	wh = this._smoothBackgroundScroll.wh
    	ih = this._smoothBackgroundScroll.ih;
    	st = $(document).scrollTop();
    	posy = (dh - ih) * st / (dh - wh);
    	document.body.style.backgroundPosition = 'center ' + posy + 'px';
    }

    You can find it here along with example and visual explanation what's really going on with image and document:

    Smooth background image scrolling

提交回复
热议问题