【问题标题】:How to execute JavaScript code after dynamic image height is calculated?计算动态图像高度后如何执行 JavaScript 代码?
【发布时间】:2013-03-13 01:05:09
【问题描述】:

我正在开发一个图像很重的响应式网站。为了论证,想象一下像 Pinterest 这样的图像网格。在这些图像之上分层的是包含基本元数据(如标题、作者等)的 div,我在缩略图图像中动态垂直居中。

我正在使用 JavaScript 动态计算(因为我不知道某人正在访问网站的视口大小和/或他们是否调整了浏览器寡妇的大小)缩略图的高度并使 div 居中元数据。

除了一件事之外,这种方法似乎工作得很好,我怀疑这是问题所在......?当页面最初加载包含元数据的 div 时,从图像容器的底部开始,然后在图像高度和图像中心由 JavaScript 确定后向上移动。实际上,从用户体验的角度来看,看到这种“打嗝”的发生看起来并不那么好。我想我需要实现某种回调函数或延迟,以便仅在计算图像缩略图高度之后应用应用于元 div 的 CSS。

以下是我的 HTML、CSS 和 JavaScript 的 sn-ps,可帮助您了解我的代码发生了什么。如果您需要进一步澄清任何部分,请告诉我:

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,以防您看到任何 mixins 或变量)

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);

【问题讨论】:

  • 你能用那个做一个小fiddle吗?
  • 这可能是相关的:stackoverflow.com/q/3877027/901048
  • 你是如何获取图像的?是在the_post_thumbnail('main') php 调用中吗?
  • @abbood - 是的,这是一个 WordPress 功能。

标签: javascript jquery html css


【解决方案1】:

您正在使用 php 获取图像。您可以使用 jQuery.ajax() 从图像服务器异步获取图像,然后在此示例中使用 ajax() 回调方法,如 done()

$.ajax({
  url: "http://yourImageServer/image.png"
}).done(function ( data ) {
   // your callback method here
});

您可以在此处插入已知图像高度和宽度等的元信息。同时您可以使用微调器预加载这些 div。

【讨论】:

    猜你喜欢
    • 2011-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-12
    • 2016-12-28
    • 1970-01-01
    • 2015-06-17
    • 1970-01-01
    相关资源
    最近更新 更多