覆盖在“背景大小:包含”上的响应式 DIV - 解决警报触发的问题
Responsive DIVs overlaying on "background-size: contain" - solve the issue where the alert fires
问题:
我正在使用一个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 === 350px
和height === 325px
.
您正在检查这两行中是否width > height
和height > 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 这里
另外,对于我认为更干净的代码,尽管是更复杂的修复,请在此处查看此小提琴
相关文章:
- 为什么“outerHTML”更改的DIV仍然没有响应
- 覆盖在“背景大小:包含”上的响应式 DIV - 解决警报触发的问题
- 将 AJAX 响应文本加载到 DIV 中
- 在单独的DIV中显示JQueryAjax响应的不同部分
- 显示AngularJs中响应的Div
- 在ActionPerformed上添加Div响应
- ajax php中的Div响应
- 根据服务器响应更改DIV
- 响应行不尊重其内部DIV的高度
- HTML CSS,引导响应DIV高度
- 用响应性动画化Div
- 位置Div在背景图像的顶部(覆盖/响应)
- 响应式设计:Div高度没有在窗口大小调整时更新
- 响应HTML元素,使用jQuery更改DIV的背景和文本
- 在AngularJS中,如果远程资源的响应状态是403(禁止),我如何隐藏DIV
- Div没有响应jQuery函数
- 获取Div位置与响应式布局
- 如何使用角度响应数据设置DIV的背景图像
- 如何使用$.ajax()函数从搜索栏中获取URL并在DIV中显示HTML响应
- 使用jQuery在每个链接后将PHP响应加载到DIV中