gpt4 book ai didi

javascript - 当 background-size 被覆盖时,如何获取当前 "real"背景图像大小?

转载 作者:行者123 更新时间:2023-11-28 15:23:16 24 4
gpt4 key购买 nike

之前可能有人问过这个问题,我尝试了这个帖子中给出的答案:How to get dimensions for a background image when background-size is set to contain?

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

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

1920/1080 为我们提供了大约 1.7 的比率,因此每当浏览器 widow 进行缩放时,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;
}
});
});

注意:我正在使用 this用于检测容器 div 元素大小变化的小型库,因为 jQuery 的调整大小处理程序只能绑定(bind)到窗口对象。

关于javascript - 当 background-size 被覆盖时,如何获取当前 "real"背景图像大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45688747/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com