我在创建个人网站时发现了一个错误,在 Firefox 或 Chrome 上使用我的 Android 手机时,页面会在第一次正确加载,但当我刷新页面时,它会加载不同。
我正在使用 jQuery 动态确定视口(viewport)的大小,从而将内容正确放置在视口(viewport)下方。最终发生的事情似乎是该函数查看高度为 0 的图像并将内容放在页面的最顶部,而不是将其定位在图像下方。如果我向下滚动页面并向上滚动,图像就在那里。
这不会发生在我的桌面上,所以它似乎是特定于移动设备的。
执行动态调整大小的 jQuery 函数如下所示。
// This line simply puts the content below the image at either the viewport height
// or the image height, depending on whether the image height is larger than the viewport
var height = $(window).outerHeight() < $('.jumbotron-img').innerHeight() ? $(window).outerHeight() : $('.jumbotron-img').innerHeight();
$('#header-img-container').css('height', height);
对应的HTML
</div>
<div id='header-img-container'>
<img src='images/site_skyline.jpg' class='img-fluid jumbotron-img'>
<h1 class='d-flex justify-content-center fixed-top' id='main-header'>My Name</h1>
</div>
最佳答案
发生这种情况是因为您似乎在加载图像之前获取了容器的高度。在您的浏览器中,图像可能以某种方式缓存,这就是为什么您看不到与在移动设备中相同的原因。
要确保所有内容都已加载并获得正确的容器高度,您可以在 window.load()
方法中调用您的函数。
根据您的 jQuery 版本,您可以:
$( window ).load(function() {
var height = $(window).outerHeight() < $('.jumbotron-img').innerHeight() ? $(window).outerHeight() : $('.jumbotron-img').innerHeight();
$('#header-img-container').css('height', height);
});
或者,如果您想针对特定图像进行优化,您可以在仅加载图像时调用 load 方法......就像这样
$( ".jumbotron-img" ).load(function() {
alert('image loaded');
});
您可能希望使用一个 id 来避免使用 jumbotron-img 类,以防您有多个 id 并且需要具体说明。
您可以在 .load()
上找到更多信息 here
关于javascript - 第二次加载时网站在移动设备上的加载方式不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50616189/