0

複数の背景画像を持つ複数の div があり、以下のコードのようにそれらをプリロードしたいとしましょう。一部のドキュメントでは、これらの背景画像のすべてを使用していないため、ドキュメントで使用されていない場合でも常に読み込まれる大量の背景画像を事前に定義するのではなく、ドキュメントに表示されるものだけをプリロードする方が理にかなっています。

画像をロードするこのコードがありますが、画像が使用されている場合にのみ画像をロードしたいと思います。

$(document).ready(function()
{
    var img = document.createElement('img');

    img.onload = function()
    {
        console.log("%o finished loading", this);
        //Set mouseover/mouseout event here
    };

    img.src = 'image.png', 'image2.png', 'image3.png'; // i realized that i have no idea how to add more images
});
4

1 に答える 1

1

データベースを使用するか、表示しているドキュメントに関連する配列を渡すだけで、画像配列を JavaScript に動的にフィードすることをお勧めします。

したがって、次のような関数を使用できます。

var BuildImages = function(imgs)
{
  for(var i = 0; i < imgs.length; i++)
  {
    var img = document.createElement('img');

    img.load(function(e)
    {
       console.log("%o finished loading", this);
       //Set mouseover/mouseout event here
    });

    img.src = imgs[i];
  }
}

そして、次のようにドキュメントから呼び出します。

$(document).ready(BuildImages(new Array('image.png', 'image2.png', 'image3.png')));

//// アップデート

var buildImages = function(divsclassname, imgs)
{
  var i = 0;
  // Loop through all divs with the class name you pass into this function
  $('.'+divsclassname).each(function(e)
  {
    // Check for has-image
    if(!$(this).hasClass('has-image'))
    {
      // If not found then set the background image and add class
      $(this).css('background-image', imags[i]).addClass('has-image');
    } 
    i++;
  });
}

divのクラス名を設定することを加えて、同じ方法で関数を呼び出します

$(document).ready(function(e)
{
  // Define your images in an array
  var images = new Array('image.png', 'image2.png', 'image3.png');

  // pas in the images and the classname of the divs you want to have bg images
  buildImages('yourdivsclassname', images));
});
于 2011-04-11T10:04:46.037 に答える