【发布时间】:2026-02-10 16:55:02
【问题描述】:
所以我已经阅读了许多针对同一问题的其他解决方案,但它们似乎都不起作用。
我有一堆图片,其中大部分在页面加载时都被隐藏了。只有第一个图像是可见的。我需要做的是给他们一个负的上边距以使图像垂直居中。唯一的问题是,我现在拥有的代码非常不一致,并且只能时不时地工作。我实际上不确定这是我的代码还是图像正在被缓存或其他什么。
这就是我所拥有的:
$('#frontpage-sidebar-slideshow img').each(function(i, v) {
// I read that preloading the images would solve the problem, but this doesn't do anything
//var src = $(this).attr('src');
//$('<img/>')[0].src = src;
// First make parent .slide visible to be able to get the image dimentions (not possible if image is invisible)
var showAfter = false;
if(!$(this).parent('.slide').is(':visible')) {
showAfter = true;
$(this).parent('.slide').css({ // .show() might also work
display: 'block',
visibility: 'visible',
opacity: 1
});
}
// Get dimentions
var wrapHeight = parseInt($('#frontpage-sidebar-slideshow').height(), 10) + 20;
var imgHeight = $(this).height();
var offset = Math.ceil((wrapHeight - imgHeight) / 2);
// Set offset if needed
if(imgHeight > wrapHeight) {
$(this).css('margin-top', offset);
}
// Show image again if needed
if(showAfter) {
$(this).parent('.slide').show();
}
});
我正在使用 SlidesJS 创建图像的幻灯片。 HTML 格式如下所示:
<div class="slide">
<a href="url goes here">
<img width="200" src="image src goes here" alt="" style="">
<div class="overlay">
<p class="title"> Some title </p>
<p> Some content </p>
<p> More content </p>
</div> <!-- overlay -->
</a>
</div>
<div class="slide" style="display: none;"> <!-- Only the first image is visible, so this one will be hidden -->
<a href="url goes here">
<img width="200" src="image src goes here" alt="" style="">
<div class="overlay">
<p class="title"> Some title </p>
<p> Some content </p>
<p> More content </p>
</div> <!-- overlay -->
</a>
</div>
有两个问题:
1) 第一张图片的高度结果非常不一致。有时我得到包装器值(.slide 的高度),有时我得到实际高度值。我不知道是什么原因造成的。
2) 无论我做什么,我只得到第一张图像的高度值。其余图像仅返回0。是的,他们甚至不返回包装器的高度(.slide 的高度),这很奇怪。
有什么想法吗?
更新我刚刚意识到 SlidesJS 和我的脚本都在页面加载时运行,它们可能会发生冲突(我正在尝试显示图像,获取它们的大小,然后隐藏它们,而 SlidesJS 想要隐藏除第一个之外的所有脚本),所以我尝试将上面的整个脚本包装在 setTimeout(code, 300) 中,现在它至少似乎为我提供了第一张图像的一致结果,但其余图像仍然返回 0。
【问题讨论】:
标签: jquery image hidden image-size