当滚动条出现时,HTML背景图像会改变大小

时间:2016-02-24 21:52:47

标签: html css background-image

我在我网站的所有页面上使用此背景图片:

body {
    background-image:url('...');
    background-attachment: fixed;
    background-repeat: no-repeat;
    background-size: cover;
}

这适用于每页。但是,在使用和不使用垂直滚动条的页面之间切换时,页面宽度会发生变化,这会导致背景图像的大小略有变化,从而相应地缩放。

这个小小的转变是令人不快的,我想避免它。我该怎么办?我有办法让背景图像“忽略”滚动条占用的空间吗?

2 个答案:

答案 0 :(得分:1)

我遇到了同样的问题,并通过纯CSS解决了我的所有问题。每种方案都以某种方式失败最后,我决定创建一个小型JavaScript代码段,利用100vw和100vh单位,在具有或不具有垂直滚动条的页面之间切换时摆脱背景跳跃。

如果您使用background-size: 100vw 100vh,则背景图片不会保持其宽高比。同样,如果您使用background-size: 100vw autobackground-size: auto 100vh,图片将保持其宽高比,但可能并不总是填满整个屏幕,具体取决于图像和屏幕尺寸。

此脚本会将cover更改为100vw autoauto 100vh,具体取决于哪一个将填满整个屏幕。该脚本重量很轻,因为它在页面加载时执行一次,并且每次调整窗口大小时都会执行。



// Function to change background size "cover" to
// either "100vw auto" (100 percent of viewport
// width and automatic height)
// or "auto 100vh" (automatic width and 100
// percent of viewport height).
fixBackgroundSizeCover = function(event) {

  var bgImageWidth = 3639,
    bgImageHeight = 2255,
    bgImageRatio = bgImageWidth / bgImageHeight,
    windowSizeRatio = window.innerWidth / window.innerHeight;

  if (bgImageRatio > windowSizeRatio) {
    document.body.style.backgroundSize = 'auto 100vh';
  } else {
    document.body.style.backgroundSize = '100vw auto';
  }
};

// Execute the fix function once upon load
fixBackgroundSizeCover();

// Execute the fix function everytime on window resize
window.addEventListener('resize', fixBackgroundSizeCover);

// A test button to toggle body vertical scrollbar on and off
document.getElementById('toggle-body-vertical-scrollbar-btn').addEventListener('click', function(event) {
    if(document.body.classList.contains('force-scrollbar')) {
      document.body.classList.remove('force-scrollbar');
    } else {
      document.body.classList.add('force-scrollbar');
    }
});

body {
  background-image: url("https://unsplash.com/photos/Fr9WHTRMY5A/download");
  background-attachment: fixed;
  background-repeat: no-repeat;
  background-size: cover;
}

/* The following is related to the toggle body vertical scrollbar button */
body.force-scrollbar {
  min-height: 2000px;
}

#toggle-body-vertical-scrollbar-btn {
  position: fixed;
  top: 10px;
  left: 10px;
  padding: 10px;
  background: rgba(255,255,255,.7);
  border: none;
  border-radius: 4px;
  box-shadow: 0 2px 2px rgba(0,0,0,.2);
  color: #222;
  font-family: sans-serif;
  cursor: pointer;
}

#toggle-body-vertical-scrollbar-btn:hover {
  background: rgba(245,245,245,.85);
  box-shadow: 0 1px 1px rgba(0,0,0,.2);
}

<button id="toggle-body-vertical-scrollbar-btn">
    Toggle body vertical scrollbar
</button>
&#13;
&#13;
&#13;

代码段具有硬编码的背景图像宽度和高度,因为图像大小事先已知。如果加载动态背景图像,则需要以某种方式计算背景图像的纵横比。

https://jsfiddle.net/perttumyry/0csjk8yo/

答案 1 :(得分:0)

在其上添加自己的滚动条,浏览器不会在滚动后添加另一个滚动条

如果您不知道这是什么代码使用 - https://css-tricks.com/custom-scrollbars-in-webkit/

或使用并制作自己的 - http://mikethedj4.github.io/Webkit-Scrollbar-Generator/

相关问题