首页 > 解决方案 > 是否可以使用 html 中的 img 标签来做视差效果,还是必须由背景来做?

问题描述

我是处理css / html的新手,我试图做一些边界半径中包含的视差效果,但每次我尝试使用背景(url)做它似乎并没有做我想要的,所以我想知道是否可以从 img 标签中做到这一点?

标签: htmlcss

解决方案


您可以使用 JS 解决您的问题。看看下面的例子。它会为你工作。祝你今天过得愉快。

$('.img-parallax').each(function() {
  var $image = $(this);
  var $imageParent = $(this).parent();

  function parallaxImg () {
    var speed = $image.data('speed');
    var imageY = $imageParent.offset().top;
    var winY = $(this).scrollTop();
    var winH = $(this).height();
    var parentH = $imageParent.innerHeight();
    // The next pixel to show on screen      
    var winBottom = winY + winH;

    // If block is shown on screen
    if (winBottom > imageY && winY < imageY + parentH) {
      // Number of pixels shown after block appear
      var imgBottom = ((winBottom - imageY) * speed);
      // Max number of pixels until block disappear
      var imgTop = winH + parentH;
      // Percentage between start showing until disappearing
      var imgPercent = ((imgBottom / imgTop) * 100) + (50 - (speed * 50));
    }

    $image.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://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="block">
  <img src="https://unsplash.it/1920/1920/?image=1003" data-speed="-1" class="img-parallax">
  <h2>Parallax 1</h2>
</div>

<div class="block">
  <img src="https://unsplash.it/1920/1920/?image=1002" data-speed="1" class="img-parallax">
  <h2>Parallax 2</h2>
</div>

<div class="block">
  <img src="https://unsplash.it/1920/1920/?image=1014" data-speed="1" class="img-parallax">
  <h2>Parallax 3</h2>
</div>


推荐阅读