0

有时我会遇到问题,试图获取有问题的 HTML 元素的大小。

我正在跟踪 JavaScript 代码,看到这个元素的宽度和高度返回为 0。

当我在浏览器的控制台中执行相同的代码时,会返回正确的大小。

演示此问题的示例代码如下:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8" />
    <title>Decorate image with button</title>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js" type="text/javascript"></script>

    <script type="text/javascript" charset="utf-8">
        jQuery(function($){
            // Decorate image, wrapped to link to movie with "Play" button
            $("a > img").each(function(){
                var img = $(this);
                var a = img.parent();

                var w = img.width();
                var h = img.height();

                a.html(" \
                    <table style='position: absolute;'> \
                        <tr style='background-color:transparent;'> \
                            <td style='width: 100%; background-color: transparent;'> \
                                <img src='http://30ttclan.extra.hu/e107_images/RTEmagicC_play_button.png.png' style='display: block; width: 25%; margin-left:auto; margin-right: auto;'></img> \
                            </td> \
                        </tr> \
                    </table>");
                a.append(img);
                // Make height of table equals to height of image
                a.find("> table").width( w );
                a.find("> table").height( h );
            });
        });
    </script>
</head>
<body>
    <a href="http://movies.apple.com/media/us/mac/ilife/iphoto/2010/features/apple-ilife-iphoto-features_whats_new-us-20100727_r848-9cie.mov">
        <img src="http://kelsocartography.com/blog/wp-content/uploads/2009/01/iphoto09_map.png">
    </a>
</body>
</html>

这段代码需要一个图像,包裹在锚点上并用“播放”按钮装饰它,它必须居中。

表格单元格用于居中。

在 Firefox 中它运行良好,但在 Safari 5 中则不行。

当我们跟踪代码时,“w”和“h”变量获取宽度和高度时,我们会看到它们的值为零。

当我们从浏览器的控制台说

$("a > img").width()

我们将获得正确尺寸的图像。

我想,我错过了一些东西......

我认为,我必须捕捉“渲染完成”之类的事件......但是,据我所知,它们并没有出现在 DOM 中。

我如何才能知道,当 HTML 元素被渲染并显示为 100% 确定时,我正在处理正确的尺寸?

4

1 回答 1

2

问题已经解决了。

正如问题中提到的,如何确保在 JQuery 插件中加载图像?

像 Chrome 这样的 webkit 浏览器通常会为图像返回 0 大小,因为它们是并行加载的。

所有,我需要做的是对图像使用“加载”事件。

$("a > img").load(function(){
    var img = $(this);
    var a = img.parent();

    var w = img.width();
    var h = img.height();

    a.html(" \
        <table style='position: absolute;'> \
            <tr style='background-color:transparent;'> \
                <td style='width: 100%; background-color: transparent;'> \
                    <img src='http://30ttclan.extra.hu/e107_images/RTEmagicC_play_button.png.png' style='display: block; width: 25%; margin-left:auto; margin-right: auto;'></img> \
                </td> \
            </tr> \
        </table>");
    a.append(img);
    // Make height of table equals to height of image
    a.find("> table").width( w );
    a.find("> table").height( h );
});

现在,我得到了正确的尺寸。

于 2010-10-22T06:23:51.390 回答