开发者

Replacing one image with another image through ajax makes it dissappear for a split second

I have the following code (asp.net-mvc, jquery) (i have simplified the example to show the issue) where i want开发者_开发知识库 to click on an image and have it replaced with another image.

This works fine but the first time i click it, the original image disappears (for a split second) before the other image shows up. After that it works seamlessly.

Is there any way to eliminate this quirk so there is not split second where no image is shown?

Here is my controller code:

    public ActionResult UpdateFavoriteExercise(int id, string toggle)
    {
        if (toggle == "off")
        {
            return Content("<img toggle='off' src='/images/vote-favorite-off1.png' border=0'>");
        }
        return Content("<img toggle='on' src='/images/vote-favorite-on1.png' border=0'>");
    }

Here is my jquery code:

$('div.favoriteExercise').live('click', function() {

    var id = $(this).attr("id");

    var toggle = $(this).attr("toggle");
    if (toggle == 'off') {
        onOff = 'on';
    }
    else {
        onOff = 'off';
    }

    var url = '/Tracker/UpdateFavoriteExercise/' + id + '?toggle=' + onOff;

    $(this).load(url);
    $(this).attr("toggle", onOff);
});


You could try preload the new image with javascript, without javascript or with css.

Another option is to use sprites that ensure the image is already loaded.

These are just a few tricks you can try, there are plenty more if you do a bit of googling :)

In fact, I'd suggest using a single sprite on a single element, and then using background-position in the CSS to switch the focus. That way, you can just add/remove a single class from the element, without having to add/remove new elements and do all that testing logic.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜