【问题标题】:(CSS) Make a background image scroll slower than everything else(CSS)使背景图像滚动比其他所有内容都慢
【发布时间】:2015-05-28 04:49:11
【问题描述】:

这是我的正文 CSS 代码:

body {
  padding: 0;
  margin: 0;
  background-image: url("../images/background.jpg");
  background-repeat: no-repeat;
  background-color: grey; 
  background-size: 100%;
}

我想要做的是让图像滚动的速度比页面上的其他所有内容都慢,从而产生简单的视差效果。我在网上查了一下,我看到的所有例子都比我想要的复杂得多。

【问题讨论】:

标签: css background parallax effect


【解决方案1】:

我还在寻找一种现代且直观的方法来调整我的背景滚动速度。您应该试试受 Spotify.com 启发的 Simple Parallax Scrolling jQuery Plug-in

将它附加到您的项目后,连同一张大图像一起玩,这是设置它的众多方法之一。

HTML |在元素上设置容器和基本视差属性。

<main>
<section>Some Content Above it</section>
 <div class="parallax-container" data-parallax="scroll" data-position="top" style="height: 80vh;"></div>
<section>Some Content Below it</section>
</main>

jQuery |在这里,您可以根据文档使用其他参数

function parallaxjs() {
    $('.parallax-container').parallax({
        imageSrc: '/<path-to-your-image>/<your-big-image>.jpg',
        naturalWidth: 1071, //your image width value
        naturalHeight: 500, //your image height value
        bleed: 0,
    });
}

(function () {
  parallaxjs();
})($);

【讨论】:

    【解决方案2】:

    我知道这已经很晚了,但我想知道它会不会比上面的代码更容易工作,并投入了 15 分钟的时间。
    这是我的代码:

    document.getElementById("body").onscroll = function myFunction() {  
        var scrolltotop = document.scrollingElement.scrollTop;
        var target = document.getElementById("main1");
        var xvalue = "center";
        var factor = 0.5;
        var yvalue = scrolltotop * factor;
        target.style.backgroundPosition = xvalue + " " + yvalue + "px";
      }
    #main1 {
        background-image: url(https://images.unsplash.com/photo-1506104489822-562ca25152fe?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9);
        background-position: top center;
        background-attachment:scroll;
        background-size: cover;
        height: 80vh;
        width: 100%;
    }
    #placeholdersoyoucanscroll{
        height:100vh
    }
    <body id="body">
          <main>
            <div id="main1">
            </div>
            <div id="placeholdersoyoucanscroll">
            </div>
        </main>
    </body>

    【讨论】:

    • 工作完美,比处理转换简单得多。
    • 完美答案!奇迹般有效。如果要更改背景图片滚动方向,请将target.style.backgroundPosition = xvalue + " " + yvalue + "px";这行代码替换为target.style.backgroundPosition = xvalue + " -" + yvalue + "px";
    • 谢谢蒂姆!将background-attachment: scroll 更改为background-attachment: fixed,修复了一个小的延迟并使其变得更好。
    【解决方案3】:

    你可以在这里使用一些简单的东西: html:

    运动

    css:

    body {
    
      min-height:4000px;
      background-image: url("http://www.socialgalleryplugin.com/wp-content/uploads/2012/12/social-gallery-example-source-unknown-025.jpg");
    }
    
    h1 {margin-top:300px;}
    

    js:

    (function(){
    
      var parallax = document.querySelectorAll("body"),
          speed = 0.5;
    
      window.onscroll = function(){
        [].slice.call(parallax).forEach(function(el,i){
    
          var windowYOffset = window.pageYOffset,
              elBackgrounPos = "50% " + (windowYOffset * speed) + "px";
    
          el.style.backgroundPosition = elBackgrounPos;
    
        });
      };
    
    })();
    

    这里是jsfiddle

    【讨论】:

    • 是否有可能保持背景的水平放置不变?我将其用于英雄图像,我需要根据屏幕大小使用background-position 轻推。否则,很好的解决方案!
    【解决方案4】:

    【讨论】:

    • 不正确,使用 CSS 已经有很多年了。见here
    【解决方案5】:

    我意识到这是一个老问题,但是,我最近自己偶然发现了这个问题,并花了很多时间试图找到最好的工作代码。我发现的所有东西要么太复杂,要么无法正常工作,尤其是在 Chrome 中。正如其他人指出的那样,纯CSS无法解决问题,但我自己制作了简单的AngularJS指令来解决问题:

    app.directive("paraBack", ['$window', function ($window) {
      return function(scope, element, attrs) {
        element.css("background-image", "url("+attrs.paraBack+")"); // Apply the background image with CSS
        element.css("background-attachment", "fixed"); // Disable background scrolling
    
        var max = Infinity;
    
        var image = new Image(); // Create a JavaScript image so that the code below can be run when the background is loaded
        image.src = attrs.paraBack;
        image.onload = function () {
          max = image.height - window.innerHeight; // Stop scrolling after the bottom of the picture is reached
          var xOffset = -(image.width/2-window.innerWidth/2);
          element.css("background-position-x", xOffset+'px'); // Horizontally align the background
        }
    
        var scrollHandler = function () {
          var offset = Math.floor(this.pageYOffset*0.1); // Set background to scroll at 10% of scrolling speed
          if (offset<max) {
            element.css('background-position-y', '-'+offset+'px'); // If not the bottom of the image is reached, move the background (scroll)
          }
        };
    
        angular.element($window).on('scroll', scrollHandler); // Set the defined scrollHandler function to be ran when user scroll
    
        scope.$on('$destroy', function () {
          angular.element($window).off('scroll', scrollHandler); // Unbind the function when the scope is destroyed
        });
      };
    }]);
    

    它可以像这样在html中使用:

    <body para-back="url/to/image">
    

    如果您想查看它的外观示例,可以访问this page

    【讨论】:

      【解决方案6】:

      我偶然发现这一点是为了在我用纯 CSS 创建的视差速度上寻找更大的灵活性,我只想指出所有 这些人都错了,纯 CSS 是可能的也可以更好地控制元素的高度。

      您可能需要稍微编辑您的 DOM/HTML 以拥有一些容器元素,在您的情况下,您将背景应用于主体,这会限制您很多并且看起来不是一个好主意。

      http://keithclark.co.uk/articles/pure-css-parallax-websites/

      以下是根据屏幕尺寸使用视口百分比长度控制高度的方法:

      https://stanhub.com/how-to-make-div-element-100-height-of-browser-window-using-css-only/

        .forefront-element {
          -webkit-transform: translateZ(999px) scale(.7);
          transform: translateZ(999px) scale(.7);
          z-index: 1;
        }
      
        .base-element {
          -webkit-transform: translateZ(0);
          transform: translateZ(0);
          z-index: 4;
        }
      
        .background-element {
          -webkit-transform: translateZ(-999px) scale(2);
          transform: translateZ(-999px) scale(2);
          z-index: 3;
        }
      

      图层速度由透视和 Z 平移值的组合控制。具有负 Z 值的元素将比具有正值的元素滚动慢。该值距离 0 越远,视差效果越明显(即 translateZ(-10px) 的滚动速度将比 translateZ(-1px) 慢)。

      这是我通过谷歌搜索找到的一个演示,因为我知道那里有很多非信徒,永远不要说不可能:

      http://keithclark.co.uk/articles/pure-css-parallax-websites/demo3/

      【讨论】:

      • 我想澄清一下,如果您担心浏览器兼容性,这仍然不是一个好的解决方案。在撰写本文时最新的 Firefox/Chrome 上,每个容器的左侧都有一个白条。此外,在 Chrome 上,背景元素显得非常模糊。虽然效果出现了,但与 JS 方案相比,视觉效果还是欠缺的,因此这种纯 CSS 方案是行不通的。
      • 这也改变了移动设备的滚动效果。 i:e iPad 和 iPhone 在您松开触摸后不会继续滚动,感觉很粘。然而,与 Jquery 视差技术不同的是,这适用于包括 safari 在内的所有浏览器。
      • 滚动问题仍然存在 - 有什么办法可以摆脱这种“粘性”?
      • @CMG 我不认为白条是由于兼容性问题;当您说“背景元素看起来很模糊”时,我不明白您在说什么,因为事实并非如此here;至于浏览器兼容性,IE11 不支持这种方法(但现在谁还在使用 IE?),但 browser compatibility for CSS 3D transforms - 我认为 - 足够好。浏览器兼容性不是问题,但询问了 CSS 解决方案
      【解决方案7】:

      如果要应用高背景图片,使用这个JS:

      (function () {
              var body = document.body,
                      e = document.documentElement,
                      scrollPercent;
              $(window).unbind("scroll").scroll(function () {
                  scrollPercent = 100 * $(window).scrollTop() / ($(document).height() - $(window).height());
                  body.style.backgroundPosition = "0px " + scrollPercent + "%";
              });
      })();
      

      【讨论】:

      • 这很简单而且效果很好。也不同于纯 css 解决方案,它并不模糊和可怕的外观。 +1
      • 如果这包括“不需要”将 jquery 附加到项目的原始 javascript 方法,我会赞成这个答案。
      【解决方案8】:

      同意仅使用 css 是不可能的,因为您必须计算图像和文档的高度比。 我也喜欢这种效果,这就是为什么创建了一个简单的函数来做到这一点。这是函数及其对滚动事件的调用:

      $(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';
      }

      您可以在此处找到它以及示例和视觉说明图像和文档的实际情况:

      Smooth background image scrolling

      【讨论】:

      • 不正确,使用 CSS 已经有很多年了。见here
      猜你喜欢
      • 2018-04-03
      • 1970-01-01
      • 2012-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-22
      • 2015-07-04
      • 1970-01-01
      相关资源
      最近更新 更多