这是故事......
我在1174px x 375px尺寸的容器中有一个尺寸为1174px x 660px的图像。当我设置隐藏在容器上的溢出时,图像的高度被截止并且仅显示图像高度的375像素。
我创建了一个JavaScript函数,该函数获取此图像(1174x660)并将其垂直居中于其容器(1174x 375)中,以便图像的中心位于容器的中心。
function allFeaturesImagesResize () {
var allFeatures = function () {
var image = $('.all-features article img'),
container = $('.all-features article'),
container_height = container.height(),
image_height = image.height(),
container_center = .5 * container_height,
image_center = .5 * image_height,
center = (image_center - container_center);
image.css('position','relative').css('bottom', center);
}
$(function () {
$(window).resize(function () {
allFeatures();
}).resize();
});
}
我在这个函数周围使用$(document).ready(function() { //... });
包装器,但是,每当页面加载时,我都可以看到函数执行将图像移动到中心点的工作。在重新定位完成之前,有没有办法延迟加载?
请记住,我的网站是流畅的响应,这就是为什么我需要动态定位图像,因为我不知道用户的视口预先尺寸(特别是宽度)。
答案 0 :(得分:1)
使用load
代替ready
事件。 $(window).load(function(){ ... your code }
将告知只有在加载所有图像后才能执行代码。即使图像未完成加载
ready
事件
请注意,您正在选择多个图片$('.all-features article img')
。通过images.height()
,它只会获得第一个找到的图像的高度。对于选择多个容器的行也是如此。
您的代码应转换为“为每个找到的图片做”:$('.all-features article img').each (function(){...});