简体   繁体   中英

Loading bar while image loads from getElementById

Below I have some code for a comic website I'm maintaining. When you click various buttons or select a page from the drop down menu the image changes to the corresponding image. However the image remains on the previous image until the new one has loaded. Is there any way I can add a loading bar or one of the spinning circle things until it has happened?

FYI, I'm not heaps advanced with JS, and this is my own code creation. Help much appreciated.

// Drop Down Menu, next and previous buttons

// Buttons
$(document).ready(function () {
    var dd = $('#HailComic');
    var max_len = dd.find('option').length;
    $('#nextpage').click(function () {
        var x = dd.find('option:selected').index();
        if (max_len == x + 1) x = -1;
        dd.find('option').eq(x + 1).prop('selected', true);
        document.getElementById("hail_image").src="images/comic/hail_" + HailComic.options[HailComic.selectedIndex].value + ".jpg";
    });
    $('#previouspage').click(function () {
        var x = dd.find('option:selected').index();
        if (0 == x + 1) x = max_len;
        dd.find('option').eq(x - 1).prop('selected', true);
        document.getElementById("hail_image").src="images/comic/hail_" + HailComic.options[HailComic.selectedIndex].value + ".jpg";
    });
    $('#lastpage').click(function () {
        var x = max_len;
        dd.find('option').eq(x - 1).prop('selected', true);
        document.getElementById("hail_image").src="images/comic/hail_" + HailComic.options[HailComic.selectedIndex].value + ".jpg";
    });
    $('#firstpage').click(function () {
        dd.find('option').eq(0).prop('selected', true);
        document.getElementById("hail_image").src="images/comic/hail_001.jpg";
    });
});




// List Changing
$(document).ready(function(){
    // Select
    var changeHailImage = function () { 
    document.getElementById('hail_image').src = "images/comic/hail_" + this.options[this.selectedIndex].value + ".jpg"
    }

    var HailList = document.getElementById('HailComic');
    HailList.addEventListener('change', changeHailImage, false);
});

You an use img.load() function to achieve this. Please check the pen http://codepen.io/anon/pen/VvwWWj

var changeHailImage = function () { 
    document.getElementById('hail_image').src = 'loading.gif';//get a loading image
    var img = new Image();
    img.src = "images/comic/hail_" + this.options[this.selectedIndex].value + ".jpg";
    img.onload = function () {
        document.getElementById('hail_image').src = img.src;
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM