我正在开发一个图像很重的响应式网站。为了争论起见,想象一下像 Pinterest 这样的图像网格。在这些图像之上分层的是包含基本元数据(例如标题、作者等)的 div,我将其动态地垂直居中在缩略图图像中。
我正在使用 JavaScript 动态计算缩略图的高度和居中的 div(因为我不知道某人正在访问网站的视口(viewport)大小和/或他们是否调整浏览器窗口的大小)其中的元数据。
除了一件事,这种方法似乎工作得很好,我怀疑这就是问题所在......?当页面最初加载时,包含元数据的 div 从图像容器的底部开始,然后在图像高度和图像中心由 JavaScript 确定后向上移动。实际上,从用户体验的 Angular 来看,这种“故障”的发生看起来并不太好。我想我需要实现某种回调函数或延迟,以便仅在计算图像缩略图高度后应用应用于 meta div 的 CSS。
下面是我的 HTML、CSS 和 JavaScript 片段,可帮助您了解我的代码的运行情况。如果您需要进一步说明任何部分,请告诉我:
HTML
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<a href="<?php the_permalink(); ?>">
<div class='meta'>
<p class='title'><?php get_the_title(); ?></p>
<p class='author'><?php get_the_author(); ?></p>
</div>
<?php the_post_thumbnail('main'); ?>
</a>
</article>
CSS(我使用 LESS 以防你看到任何混合或变量)
article {
width: 100%*(390/1174);
display: inline-block;
position: relative;
z-index: 900;
.meta {
width: 100%;
position: absolute;
left: 0;
bottom: 0;
z-index: 500;
font-size: 20px;
line-height: 1em;
text-align: center;
.title {
margin: 0;
padding: 0 16px 8px 16px;
font-size: 1em;
line-height: 1.15em;
font-weight: 700;
}
.author {
.proxima-nova;
color: white;
margin: 0;
font-size: .70em;
line-height: .825em;
}
}
a { display: block; }
}
JavaScript
var article = $('article'),
meta = $('.meta'),
meta_height = meta.height(),
article_height = article.height(),
meta_center = .5 * meta_height,
article_center = .5 * article_height,
center = (article_center - meta_center);
meta.css('bottom', center);
setTimeout(function() {
meta.show();
}, 500);
最佳答案
您正在使用 php 获取图像。您可以使用 jQuery.ajax()
从图像服务器异步获取图像,然后使用 ajax()
回调方法,例如本例中的 done()
:
$.ajax({
url: "http://yourImageServer/image.png"
}).done(function ( data ) {
// your callback method here
});
您可以在已知图像高度和宽度等的情况下插入您的元信息。同时您可以使用微调器预加载这些 div。
关于javascript - 计算动态图片高度后如何执行JavaScript代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15367085/