正文高度和水平滚动 html/css

Body height and horizontal scrolling with html/css

我正在尝试制作一个网站,该网站的背景图片在滚动时会水平移动。 我的滚动没问题,但我在调整正文大小时遇到​​问题,以便它始终适合我的图像(没有图像拼接或图像后没有白色背景),无论我的浏览器 window 的大小如何。

我已经使用 jquery 实现了滚动,并尝试在我的 css 中使用 body/section heights/widths ] 没有成功...

body {
  margin: 0;
  padding: 0;
  height: 200vh;
}

section {
  position: relative;
  width: 100%;
  height: 100%;
  background: url(https://cdn.pixabay.com/photo/2017/03/05/00/34/panorama-2117310_960_720.jpg);
  background-size: cover;
  background-attachment: fixed;
  background-repeat: no-repeat;
}
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>website.com</title>
  <link rel="stylesheet" href="style.css">
</head>

<body>
  <section></section>
  <script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous">
  </script>
  <script type="text/javascript">
    $(window).scroll(function() {
      var scroll_position = $(window).scrollTop();
      $('section').css({
        'background-position-x': -scroll_position,
      })
    })
  </script>
</body>

</html>

图像可在以下位置找到:https://pixabay.com/photos/panorama-miami-florida-water-usa-2117310/

正如你所希望看到的,根据你是否全屏,它会切片图片(对我来说,使用 body height: 200vh)或在图片后添加白色背景(300vh). 如果可能的话,我希望页面总是停在图片的末尾。

您需要考虑的是屏幕比例,因此水平和垂直滚动不同并且初始视图(viewport)不同。

计算将得到 scrollTop 比率 (只是,这就是为什么我们减去 window 的高度)相对于全高并以相同的比例水平滚动该部分(再次减去 window 的宽度)

希望不要太复杂。

完整代码如下:

$(window).scroll(function() {
  const ratio = ($(window).scrollTop() / ($('body').height() - $(window).height()));
  var scroll_position = ratio * ($('section').width() - $(window).width());
  $('section').css({
    'background-position-x': -scroll_position,
  })
})
:root {
  --viewport: 200vh;
}

body
{
  margin: 0;
  padding: 0;
}

@media (max-aspect-ratio: 2/1) {
  body {
    height: var(--viewport);
  }
  
  section
  {
    width: var(--viewport);
    height: 100vh;
    background: url(https://cdn.pixabay.com/photo/2017/03/05/00/34/panorama-2117310_960_720.jpg);
    background-size: var(--viewport) 100%;
    background-attachment: fixed;
    background-repeat: no-repeat;
    position: fixed;
  }
}

@media (min-aspect-ratio: 2/1) {
  section
  {
    height: 100vh;
    background: url(https://cdn.pixabay.com/photo/2017/03/05/00/34/panorama-2117310_960_720.jpg);
    background-size: cover;
  }
}
<script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous">
</script>
<section></section>

https://jsbin.com/gabugeg/3/edit?html,css,output

我使用 --viewport: 200vh; 变量只是为了更容易同时更改多个地方。

可以用更优化的方式编写代码,但我希望代码更具可读性。

如果一切都清楚,请告诉我。

更新

要支持奇怪的屏幕比例(在此示例中宽度/高度 = 2),您可以使用媒体查询 (min-aspect-ratio)(max-aspect-ratio: 2/1)。如果您使用不同尺寸的不同图像,您可能需要重新调整它。