通过ajax将一个图像替换为另一个图像使其在一瞬间消失

leo*_*ora 1 ajax asp.net-mvc jquery

我有以下代码(asp.net-mvc,jquery)(我已经简化了示例来显示问题)我要点击图像并将其替换为另一个图像.

这很好但是第一次单击它时,原始图像会在另一个图像显示之前消失(一瞬间).之后它无缝地工作.

有没有办法消除这个怪癖,所以没有分割秒没有显示图像?

这是我的控制器代码:

    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'>");
    }
Run Code Online (Sandbox Code Playgroud)

这是我的jquery代码:

$('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);
});
Run Code Online (Sandbox Code Playgroud)

Jer*_*iko 6

您可以尝试使用javascript预加载新图像,无需javascript使用css.

另一种选择是使用精灵确保图像已被加载.

这些只是你可以尝试的一些技巧,如果你做一些谷歌搜索有更多的:)

事实上,我建议在单个元素上使用单个sprite,然后background-position在CSS中使用切换焦点.这样,您只需从元素中添加/删除单个类,而无需添加/删除新元素并执行所有测试逻辑.