不使用CSS背景属性实现视差背景图滚动

11

如何在不使用CSS backgroundbackground-attachment 属性的情况下添加视差效果?

我在一个 div 中有一个 img 标签,并希望为图像添加视差滚动效果,以下是代码:

function resize_div()
{
    var image_height = $('.project-image img').height();

    var div_height = $('.project-image').height();
    var window_height = $(window).height();
    var window_width = $(window).width();

   
        $('.project-image').css('height', window_height - 80);
    
}

$(window).resize(function () {
        resize_div();
});
.project-details
{
  width:100%;
}
.project-image{
  text-align:center
}
.project-description
{
  line-height:15px;
  margin:0 0 10px
}
.img-responsive
{
  height: auto;
  max-width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="project-details">
  <div class="project-image">
   <img src="http://placehold.it/350X225" class="img-responsive">
  </div>  
  <h1>
  Project Title
  </h1>
  <p class="project-description">
  Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
  <br/>
  <br/>
  Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
  <br/>
  <br/>
  Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
  </p>
</div>

问题:我无法将图片放在

的背景中,所以只能使用标签来实现。

编辑:该图片在

中水平居中,并且使用自定义JavaScript在浏览器调整大小或移动/旋转平板电脑时更新图像和
大小。尝试了position:absolute和position:fixed,但似乎无效。

带有视差效果的图像

编辑-2:这是fiddle链接


@Tesseract 谢谢... 我会去看看的。 - Nishant Solanki
@NoOorZ24已添加了fiddle链接,请查看。 - Nishant Solanki
图片应该是100%的宽度吗?如果是,可见部分的高度应该是多少? - NoOorZ24
@NoOorZ24 是的,当窗口大小改变时图像高度会变化,所以无论屏幕分辨率如何,始终可以看到完整的图像和项目标题。 - Nishant Solanki
@NishantSolanki 等一下,我有点困惑,全尺寸图像应该如何实现视差效果?您希望在页面滚动时始终显示图像吗? - NoOorZ24
显示剩余4条评论
6个回答

8

不久前,我使用视差效果建立了两个例子,非常类似于您正在寻找的内容:

  • 这个例子 使用简单的jQuery在滚动时更新图像和标题的位置
  • 这个例子 仅使用CSS和3D定位来模拟图像上的视差效果

无论如何,我认为您不需要JS来在加载时调整图像大小。这里是一个使用您的代码并使用我分享的第一个示例中的jQuery代码的示例:

$( document ).ready(function() {
var $window = $(window);
function scroll_elements(){
  var scroll = $window.scrollTop();
  var scrollLayer = scroll/1.4;
  
  $(".project-image").css(
    "-webkit-transform","translate3d(0," +  scrollLayer  + "px,0)",
            "transform","translate3d(0," +  scrollLayer  + "px,0)"
  );
}

$window.scroll(scroll_elements);
});
.project-image {
  position:relative;
  z-index:1;
}
.img-responsive {
  display:block;
  max-width:100%; 
  height:auto;
  margin:0 auto;
}
h1, .project-description {
  position:relative;
  max-width:500px;
  z-index:2;
  background:rgba(255,255,255,.7);
  margin:0 auto;
  padding:10px 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="project-details">
  <div class="project-image">
   <img src="http://placehold.it/350X225" class="img-responsive">
  </div>  
  <h1>
  Project Title
  </h1>
  <p class="project-description">
  Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
  <br/>
  <br/>
  Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
  <br/>
  <br/>
  Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
  </p>
</div>


3

好的,我尝试了另一种方法,在这种情况下它有效,并且可能是最好的解决方案:

*{
  margin: 0;
  padding: 0;
}

#image {
  width: 100%;
  position: fixed;
}

#image2 {
  width: 100%;
  position: relative;
  visibility:hidden;
}
#prl {
  position: relative;
  background-color: white;
}
  <img src="http://placehold.it/350X225" id="image">
  <img src="http://placehold.it/350X225" id="image2">

<div id="prl">
  <p>
  sdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsad
  sdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksdghjlsadv  sdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsad
  sdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksdghjlsadv  sdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsad
  sdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksdghjlsadv  sdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsad
  sdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksdghjlsadv
  </p>
</div>

在这种情况下不需要使用JS,我只是使用了同一张图片两次:一张用于实际的固定消失,而另一张则是为了保留空白空间。

这是一个非常有创意的解决方案,但在我的情况下,“position:fixed”并不是解决方案,因为它会破坏所有的设计。如果没有找到任何可行的解决方案,我将接受您的答案。 - Nishant Solanki

2

在搜索一番后,我找到了这个

$('.img-parallax').each(function(){
  var img = $(this);
  var imgParent = $(this).parent();
  function parallaxImg () {
    var speed = img.data('speed');
    var imgY = imgParent.offset().top;
    var winY = $(this).scrollTop();
    var winH = $(this).height();
    var parentH = imgParent.innerHeight();


    // The next pixel to show on screen      
    var winBottom = winY + winH;

    // If block is shown on screen
    if (winBottom > imgY && winY < imgY + parentH) {
      // Number of pixels shown after block appear
      var imgBottom = ((winBottom - imgY) * speed);
      // Max number of pixels until block disappear
      var imgTop = winH + parentH;
      // Porcentage between start showing until disappearing
      var imgPercent = ((imgBottom / imgTop) * 100) + (50 - (speed * 50));
    }
    img.css({
      top: imgPercent + '%',
      transform: 'translate(-50%, -' + imgPercent + '%)'
    });
  }
  $(document).on({
    scroll: function () {
      parallaxImg();
    }, ready: function () {
      parallaxImg();
    }
  });
});
@import url(https://fonts.googleapis.com/css?family=Amatic+SC:400,700);
html, body{
  margin: 0;
  padding: 0;
  height: 100%;
  width: 100%;
  font-family: 'Amatic SC', cursive;
}
.block{
  width: 100%;
  height: 100%;
  position: relative;
  overflow: hidden;
  font-size: 16px;
}
.block h2{
  position: relative;
  display: block;
  text-align: center;
  margin: 0;
  top: 50%;
  transform: translateY(-50%);
  font-size: 10vw;
  color: white;
  font-weight: 400;
}
.img-parallax {
  width: 100vmax;
  z-index: -1;
  position: absolute;
  top: 0;
  left: 50%;
  transform: translate(-50%,0);
  pointer-events: none
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="block">
  <img src="https://unsplash.it/1920/1920/?image=1005" data-speed="-1" class="img-parallax">
  <h2>Parallax Speed -1</h2>
</div>
<div class="block">
  <img src="https://unsplash.it/1920/1920/?image=1067" data-speed="1" class="img-parallax">
  <h2>Parallax Speed 1</h2>
</div>
<div class="block">
  <img src="https://unsplash.it/1920/1920/?gravity=center" data-speed="-0.25" class="img-parallax">
  <h2>Parallax Speed -0.25</h2>
</div>
<div class="block">
  <img src="https://unsplash.it/1920/1920/?image=1080" data-speed="0.25" class="img-parallax">
  <h2>Parallax Speed 0.25</h2>
</div>
<div class="block">
  <img src="https://unsplash.it/1920/1920/?random" data-speed="-0.75" class="img-parallax">
  <h2>Parallax Speed -0.75</h2>
</div>
<div class="block">
  <img src="https://unsplash.it/1920/1920/?blur" data-speed="0.75" class="img-parallax">
  <h2>Parallax Speed 0.75</h2>
</div>


谢谢你的回答,我会将它与我的代码集成,并告诉你它是否有效。谢谢 :) - Nishant Solanki
这在我的情况下不起作用,我尝试了许多不同的计算方法在你提供的JS中,也尝试了一些CSS修补...但没有运气。 - Nishant Solanki
你遇到了什么问题? - Ismail Farooq
我已经创建了一个fiddle,请在此处查看:https://jsfiddle.net/2owd5fm9/6/ - Nishant Solanki
你实际想做什么?在这个fiddle中有不同的代码。 - Ismail Farooq
这是页面的当前代码,我希望当描述被滚动时图像能像视差一样保持不变:https://jsfiddle.net/2owd5fm9/7/ - Nishant Solanki

2

这是经过 Nishant Solanki 批准的工作示例,应该在所有浏览器中都能正常运行。

function myFunction() {
 speed = 0; 
  speed2 = -1;
  /**
  @ speed
  positive: moves up faster than background
  0: scrolls same as background
  negative: moves down faster
  -1: same as position: fixed
  try different ones to see it in action and you should figure it out
  
  P.S.
  you can apply different speeds to multiple alements to achieve what ever you desire
  */
 y = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0;
  cont = document.getElementById("prl");
  cont.style.top = (0 - Math.round(y * speed)) +"px";
  img = document.getElementById("image");
  img.style.top = (0 - Math.round(y * speed2)) +"px";
}
*{
  margin: 0;
  padding: 0;
}

#image {
  width: 100%;
  position: relative;
}
#prl {
  position: relative;
  background-color: white;
}
<body onscroll="myFunction()">

  <img src="http://placehold.it/350X225" id="image">

<div id="prl">
  <p>
  sdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsad
  sdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksdghjlsadv  sdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsad
  sdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksdghjlsadv  sdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsad
  sdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksdghjlsadv  sdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsad
  sdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksda klsadsdf sfkdl ksdghjlsadv
  </p>
</div>
</body>


我不确定其他人在SO上是否遇到了“保持滚动”的错误。在jsFiddle上它完美地工作。 - NoOorZ24

2

尽量避免在 CSS 中使用 fixedabsolute,希望你会感到自由。

function myFunction() {
  fixIt = document.getElementById('project-image');
  fixIt.style.top = 2 * Math.round(document.body.scrollTop) + "px";
}
* {
  margin: 0;
  padding: 0;
}

#project-image {
  width: 100%;
  position: relative;
}

.project-description,
.project-details>h1 {
  position: relative;
  z-index: 1;
  background: white;
}

.project-details {
  overflow: hidden
}
<body onscroll="myFunction()">


  <div class="project-details">
    <div id="project-image">
      <img src="http://placehold.it/350X225" class="img-responsive">
    </div>
    <h1>
      Project Title
    </h1>
    <p class="project-description">
      Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has
      survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
      publishing software like Aldus PageMaker including versions of Lorem Ipsum.
      <br/>
      <br/> Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen
      book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently
      with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
      <br/>
      <br/> Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen
      book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently
      with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
    </p>
  </div>
</body>

我个人非常喜欢这个现代化的插件。这里


@NishantSolanki 我运行了这段代码片段,它正常工作。它没有显示在你的桌面上吗? - Yash Yadav
@NishantSolanki 不用在意了,我觉得你选择的答案比我的更好。 - Yash Yadav

2

你可以使用像 $(window).scroll 这样简单的方法来检测窗口滚动,然后通过 .addClass.removeClass.toggleClass 来添加或删除类 - 然后在带有 scroll 的新样式下,只需更改 img 元素的位置即可。

$(document).ready(function(){
    $(window).scroll(function(){
        $('img').toggleClass('scrolled'); 
    })
})

.scrolled { 
  position: absolute;
  z-index: 777; // find correct value to use
  top: 102px; // adjust to customization
  left: 3px; // adjust to customization
}

注意:使用background图像创建此效果会更加清晰,并且可以使用.scroll调整其位置。如果您有能力重新编写一些代码以实现此目的,那么长期来看可能是值得的。如果没有,您应该能够使用jQuery .scroll.toggleClass来调整z-index:属性和position:属性。您应该使用纯CSS3进行响应式布局;如果position:属性不起作用,则可能存在与相关元素有关的太多CSS或JS的冲突。


我曾经考虑过这种解决方案,但在响应式设计中维护它相当困难。因为图像大小会根据屏幕大小而变化。 - Nishant Solanki

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接