繁体   English   中英

当背景尺寸被覆盖时,如何获得当前的“真实”背景图像尺寸?

[英]How to get the current, “real”, background image size, when background-size is cover?

之前可能有人问过这个问题,我尝试了这个线程中给出的答案: 当背景大小设置为包含时,如何获取背景图像的尺寸?

但在这种情况下, background-size设置为cover ,而不是contain

背景大小最初是1920x1080 我有一个 div 元素,它基本上总是将其宽度和高度缩放到 100%,同时如果所述 div 设置为覆盖,则背景图像。

1920 / 1080 为我们提供了大约 1.7 的比率,因此每当浏览器寡妇被缩放时,div 的宽度/高度比率也就是大于或小于 1.7。 比例不正确 - 事情破裂了。 所以我需要一种方法来计算背景图像的大小以正确设置。

编辑:这是一个 jsfiddle 的例子: https ://jsfiddle.net/ahvonenj/35pbovmz/

如果调整结果区域的大小,您可以看到结果区域本身具有一定的宽度和高度,例如 400x600。 但是,这个 400 宽度和 600 高度对于我的计算是不正确的。 我需要知道背景图像的大小。 注意背景是如何通过基本保留一些图像来保持其比例的。

只有当结果区域的宽度/高度正好是背景图像的比率时,结果区域的宽度和高度才是正确的,在这种情况下约为 1.7。

编辑 2:现在几乎可以正常工作了: https : //jsfiddle.net/ahvonenj/35pbovmz/

我自己找到了解决方案。 这是一个很好的 jsfiddle 可视化,我们分别计算容器大小和实际背景图像大小。

您可以通过从右下角拖动来调整图像容器(红色边框)的大小,并查看容器大小如何与实际背景大小分开变化: https : //jsfiddle.net/ahvonenj/o76k5jbx/

$(document).ready(function()
{
    var fullhdWidth = 1920;
    var fullhdHeight = 1080;
    var fullhdRatio = fullhdWidth / fullhdHeight; // About 1.7

    $('#wrapper').resize(function()
    {
        var containerWidth = $(this).width();
        var containerHeight = $(this).height();
        var containerRatio = containerWidth / containerHeight;
        var realWidth = null;
        var realHeight = null;

        console.log(containerWidth, containerHeight, containerRatio);

        if(containerRatio > fullhdRatio)
        {
            realWidth = containerWidth;
            realHeight = containerWidth/fullhdRatio;
        }
        else
        {
            realWidth = containerHeight*fullhdRatio;
            realHeight = containerHeight;
        }   
    });
});

注意:我使用这个小库来检测容器 div 元素的大小变化,因为 jQuery 的调整大小处理程序只能绑定到 window 对象。

我正在解决一个非常具体的问题。 我有一个背景图像, background-size: cover并覆盖另一个带有剪切蒙版的元素,该元素正在应用filter: invert()效果。

一切都是响应式的,我需要保持.centered元素上背景的位置和大小与主背景同步。

在此处输入图片说明

html {
  background: #000 url(bg.jpg) no-repeat center center fixed;
  background-size: cover;

  overflow: hidden;

  --w: 1920; // this is the size of my background
  --h: 1080;
}

.centered {
  background-image: url(bg.jpg);
  background-position: center center;
  background-size: calc(max(calc(100vh / var(--h)), calc(100vw / var(--w))) * var(--w));
  background-repeat: no-repeat;

  background-clip: text;
  color: transparent;
  filter: invert(100%)
}

基本上,这是做什么的

max(calc(100vh / var(--h)), calc(100vw / var(--w)))

是它计算封面图像高于其原始大小的大小比例:

calc(100vh / var(--h))计算视口高多少(例如0.8)
calc(100vw / var(--w))计算视口的宽度(例如 1.2)

然后,无论这些值中的哪个较大,这就是图像必须有多大才能覆盖整个视口。

之后,您只需将ratio乘以width获得当前的“真实”大小。 您还可以通过将其乘以ratio来获得“真实” height

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM