HTML元素的内容何时完全加载有事件吗?

时间:2012-02-07 23:15:51

标签: javascript jquery

我有<div>包含许多图片。我希望在所有包含的图像加载之后淡化中的<div>,因为它们构成了一个单位,我宁愿干净地显示而不是瞬间显示(加载时)

是否有类似window.onLoad的内容可以应用于某个元素?

e.g。

$("#id").onLoad(function()
{
    $(this).fadeIn(500);

});

4 个答案:

答案 0 :(得分:2)

var images = $("#id img");
var imgCount = images.size();
var i = 0; 
images.load(function() {
    if(++i == imgCount){
         $("#id").fadeIn(500);
    }
});

答案 1 :(得分:1)

这样做的一种方法是在HTML文档的head部分添加它:

$(function() {
    $("#id").fadeIn(500);
});

$(function(){/ * code * /})背后的想法是,它将在加载DOM时运行,你可以在头部获得尽可能多的这个,但它会是如果您只有一个,我会更具可读性。

另一种方法是在准备就绪时为每个页面运行一个主javascript文件,让我们调用HTML文件index.html和javascript文件index.js

的index.html

<!doctype html>
<head>
<!- include the javascript/css/etc. files -->
  <script type="text/javascript" language="javascript">
    $(function() {
      // the following function exists in index.js file
      onPageLoadedIndex();
    });

    $(function() {
      // this code will also be executed when the DOM is ready
      // however I strongly recommend having only one of these
    });
  </script>
</head>
<body>
<!-- snip -->
</body>
</html>

index.js

function onPageLoadedIndex() {
  // some code
  $("#id").fadeIn(500);
  // more code
}

通过这种方式,您将避免在HTML页面中使用过多的javascript

答案 2 :(得分:0)

您可能已经知道如何分配在页面加载时运行的函数。如果你不想,请尝试:

window.onload = function() {
    $('div').fadeIn(500);
}

仅jQuery解决方案:

    $('div img.class').load(function() {
    // img.class is your largest (in bytes) image.
        $('div').fadeIn(500);
    });

答案 3 :(得分:-1)

试试这个:

$("#id").load(function()
{
    $(this).fadeIn(500);

});
祝你好运