CSS视差效果高度达到50%

时间:2018-02-22 17:20:45

标签: html css height parallax parallax.js

我目前正在使用视差效果,它占据了首页的整个背景。 我的问题是我想将高度设置为50%..但那不起作用。

代码:

<header class="parallax-window" data-parallax="scroll" data-image-src="img/picture.jpg" alt="test">

.parallax-window {
  position: relative;
  overflow: hidden;
  width: 100%;
  height: 50%; //Not working.. why? 
}


  <script src='https://code.jquery.com/jquery-2.2.4.min.js'></script>
  <script src='https://cdnjs.cloudflare.com/ajax/libs/parallax.js/1.4.2/parallax.min.js'></script>
  <script >// SMOOTH SCROLLING
  $(function() {
    $('a[href*="#"]:not([href="#"])').click(function() {
      if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
        var target = $(this.hash);
        target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
        if (target.length) {
          $('html, body').animate({
            scrollTop: target.offset().top
          }, 900);
          return false;
        }
      }
    });
  });
  $('.parallax-window').parallax({imageSrc: 'img/picture.jpg'});
  </script>

1 个答案:

答案 0 :(得分:0)

首先关闭所有:你开始两次视差!属性data-parallax="scroll"触发自动初始化,您可以通过在javascript中调用$('.parallax-window').parallax({imageSrc: 'img/picture.jpg'});来重复此操作。此外,无需提供两次图像源!您可以使用属性data-image-src或javascript选项imageSrc。这个实际上会覆盖另一个,所以没有任何伤害,但这是不必要的。

此外,相对(或百分比)高度仅适用于父元素。如果父元素没有高度或相对高度,则在子元素中设置此属性将不起作用。这与CSS有关。您可以尝试将父元素设置为100%(例如body { height: 100%; }或绝对高度(body { height: 1200px; }),或者与查看高度相关的高度(body { height: 200vh; })。但我不会建议这样做,因为您必须保证您的内容符合规定的大小。

我宁愿使用类似的东西:

.parallax-window {
    min-height: 50vh;
}

还要确保在放入其他代码之前关闭<header>元素。否则,此代码将放在视差之前。