覆盖在“背景大小:包含”上的响应式 DIV - 解决警报触发的问题

Responsive DIVs overlaying on "background-size: contain" - solve the issue where the alert fires

本文关键字:DIV 响应 解决 问题 背景 背景大小 包含 覆盖      更新时间:2023-09-26

问题:

我正在使用一个background-size: contain图像,上面覆盖着 DIV,我希望它们相对于图像的比例和纵横比保持静止。

它可以工作,但对于浏览器宽度小于背景图像的小问题。发生这种情况时,您可以看到覆盖 DIV(分别为 .navbar#home)开始滑出位置,只是在浏览器自行更正后立即恢复到正确的位置。

我写了一个包含警报的小提琴。当浏览器宽度小于背景图像宽度时,将触发警报。您需要水平调整浏览器窗口的大小才能触发它。您可以注释掉警报以观察 DIV 偏移。

是什么原因造成的,我该如何预防?

法典:

var width = $('.bg').width();
var height = $('.bg').height();
var imgWidth = width > height ? 350/325 * height : width;
var imgHeight = height > width ? 325/350 * width : height;
var imgTop = imgHeight * .75 + ((height - imgHeight) / 2);
$('.navbar').css({
    'width': imgWidth,
    'height': imgHeight * .15,
    'top': imgTop + 'px'
});
$(window).on("resize", function() {
    width = $('.bg').width();
    height = $('.bg').height();
    imgWidth = width > height ? 350/325 * height : width;
    imgHeight = height > width ? 325/350 * width : height;
    imgTop = imgHeight * .75 + ((height - imgHeight) / 2);
    if (width < imgWidth) {
        //alert(width + 'x' + height + ', ' + imgWidth + 'x' + imgHeight);
    }
    $('.navbar').css({
        'width': imgWidth,
        'height': imgHeight * .15,
        'top': imgTop + 'px'
    });
});

它跳跃是因为:

您有一个矩形图像 - 350px X 325px。 所以这意味着width === 350pxheight === 325px.

您正在检查这两行中是否width > heightheight > width

imgWidth = width > height ? 350/325 * height : width;
imgHeight = height > width ? 325/350 * width : height;

即,您正在检查宽度(从 350px 开始)是否大于高度 (325),以及高度 (325) 是否大于宽度 (350)。

以第二个示例为例:在将窗口水平缩小 25px (350 - 325) 超过图像开始缩小的点之前,高度不会大于宽度。 因此,对于前 25px,不会重新计算高度height > width因为仍然是假的。

最简单的补救措施是简单地检查偏移量 - 检查是否width - 25 > height以及是否height + 25 > width

imgWidth = width - 25 > height ? 350/325 * height : width;
imgHeight = height + 25 > width ? 325/350 * width : height;

JSFiddle 这里

另外,对于我认为更干净的代码,尽管是更复杂的修复,请在此处查看此小提琴