计算返回多个值
问题描述:
我有一个jQuery函数,它检查子图像高度的值,然后将父级高度设置为最小图像高度的值,然后添加overflow: hidden
以避免溢出。计算返回多个值
我执行document.ready
事件的功能,但是我收到了奇怪的结果。我将获得HTMLobjectHeight,0,未定义或页面加载的正确值。为什么这是变化的?它是在图像加载之前发射的吗?我有
function setContainHeight()
{
var container = $('.com-background');
var imgs = $('.com-background img');
var smallestImg = imgs[0];
$(imgs).each(function()
{
if ($(this).height() < $(smallestImg).height())
smallestImg = $(this).height();
});
container.height(smallestImg);
container.css("overflow", "hidden");
};
的另外一个问题是,当我添加此功能可将window.resize
事件也触发对页面加载,并给出了一个不确定的结果。
HTML
<div class="com-background" style="height: 434px; overflow: hidden;">
<h1 class="community_title">Sun Lakes</h1>
<img width="250" height="167" src="http://192.168.33.10.xip.io/wp-content/uploads/2013/04/Ocotillo-lake-e1404789921289.jpg" class="wp-post-image" alt="Ocotillo - lake" style="display: block; z-index: 1;">
<img width="250" height="188" src="http://192.168.33.10.xip.io/wp-content/uploads/2013/04/Resort-e1404789892490.jpg" class="attachment-post-secondary-image-thumbnail active" alt="Resort" style="z-index: 3; opacity: 0.988634061784097;">
<img width="837" height="378" src="http://192.168.33.10.xip.io/wp-content/uploads/2014/05/homestead-error.png" class="attachment-post-tert-image-thumbnail" alt="homestead-error" style="z-index: 2;"> <div class="numeric_search">
</div>
SASS/CSS
.com-background
{
width: 100%;
position: relative;
img
{
z-index: 1;
position: absolute;
top: 0;
left: 0;
width: inherit;
max-width: 100%;
height: auto;
}
}
答
为了确保图像甲肝Ë被加载,启动一个$(window).load
事件侦听器
我还用Math.min
获得最低图像高度
$(window).on("load resize", function(event) {
// find container
var container = $(".com-background");
// get image heights in an array
var heights = container.find("img").map(function(idx, elem) {
return $(elem).height();
}).get();
// get the minimum height
var minimum = Math.min.apply(null, heights);
// set container height and overflow property
container.height(minimum).css({overflow: "hidden"});
});
答
如果你想获得的所有图像的高度,你需要确保所有的图像被下载并准备使用...要当然,你需要使用$(窗口).load()而不是$(文件).read这样的:
$(window).load(function() {
setContainHeight();
$(window).resize(setContainHeight);
});
安置自己相关的HTML和CSS了。 – akinuri 2014-10-11 23:09:38
请显示呈现的HTML,而不是PHP,除非您认为PHP是相关的。 – 2014-10-11 23:23:07