3

i have certain links, on mouse over of those links I am changing <div> background image

jQuery I have used is-

function imgchange()
    {
        $('.smenu li').mouseover( function(){
        var src = $(this).find('a').attr('href');
        $('.hbg').css('background-image', 'url(' + src + ')');
        $(this).find('hbg').attr('title', 'my tootip info');
        });     
    }

It is working fine but the problem is when I running it on server images takes 3-4 sec to be changed on change, but the second time I do mouse over images are getting changed instantly, I think this is because of browser stored images in cache. So I added one javascript to preload images on page onLoad() ivent -

<script language = "JavaScript">
function preloader() 
{
heavyImage = new Image(); 
heavyImage.src = "images/soluinfo1.jpg";
heavyImage.src = "images/soluinfo2.jpg";
heavyImage.src = "images/soluinfo3.jpg";
heavyImage.src = "images/soluinfo4.jpg";
heavyImage.src = "images/soluinfo5.jpg";
heavyImage.src = "images/soluinfo6.jpg";
heavyImage.src = "images/soluinfo7.jpg";
}
</script>

<body onLoad="javascript:preloader()">

but this script has not solved my problem.what should I do?

4

2 に答える 2

3

You might find it easier to change your approach and use CSS sprites (and another article). Then you would just have one image referenced, and you use CSS to set which part of that image gets shown in which scenario.

This assumes that the images you're using are under your control and you can use an image editor to combine them into one large image.

于 2010-07-21T09:43:53.857 に答える
3

@Richardの回答(スプライト)はおそらくあなたが求めているものに最適なものですが、コードが機能しない理由は、ほとんどのブラウザでheavyImage.src=""、実際のリクエストとしてブラウザに実際に登録するのに十分な時間が最後のものだけに与えられているためです。Imageオブジェクト設定を1 つだけ作成.srcし、ブラウザがファイルを要求するよりも速く属性をリセットしています (最新の JavaScript エンジンは、.src特にこのため、すべての中間ステートメントを削除するという追加の手順を実行していると思います)。

これを修正するには、いくつかの方法があります。Image最も簡単な方法は、画像ごとに 1 つずつ、複数のオブジェクトを作成することです。そして、それを行う最も簡単な方法は、次のようなものです。

<script type="text/javascript">
function preloader() 
{
    function doPreload(strImagePath) 
    {
        var heavyImage = new Image();
        heavyImage.src = strImagePath;
    }

    var arrImages = ["images/soluinfo1.jpg","images/soluinfo2.jpg","images/soluinfo3.jpg","images/soluinfo4.jpg","images/soluinfo5.jpg","images/soluinfo6.jpg","images/soluinfo7.jpg"];
    for (var i = 0; i < arrImages.length; i++) {
        doPreload(arrImages[i]);
    }
}
</script>

heavyImage変数を独自の関数内に配置することにより (キーワードを使用することを忘れないでください)、オブジェクトが専用のスコープ内に存在するvarことを保証します。Image

これを行う別の方法は、「ロード」イベント リスナーを単一の にアタッチすることheavyImageです。画像の読み込みが完了するたびに、次の画像を取得します。この方法の欠点は、画像が一度に 1 つずつ読み込まれることです (ナビゲーション画像には適していませんが、たとえば、画像ギャラリーには適しています)。一方、最初の手法では画像が並行して取得されます (通常は一度に 4 つ)。 .

于 2010-07-21T13:39:19.420 に答える