jquery synchronous execute

江枫思渺然 提交于 2019-12-07 18:21:48

问题


Very Sorry for my english,i have a problem.

$("#MainPicture").attr("src", url);
CenterImg();

needs to be execute line 2 code after line 1 code finished . it is asynchronous and i want the code excute by synchronous . Thanks All.

Question Details; i want to move $("#MainPicture") in the center screen when picture loaded.like this.

$("#MainPicture").attr("src", url);
// new picture width,not old picture width
var PictureWidth=$("#MainPicture").width();
var ScreenWidth=$(window).width();
var ResultWidth=(ScreenWidth-PictureWidth)/2;
$("#MainPicture").css("left",ResultWidth);

in fact,in line 2 code,i alway get old picture width.


回答1:


$("#MainPicture").attr("src", url).one('load', CenterImg );

function CenterImg() {
    var PictureWidth = $("#MainPicture").width();
    var ScreenWidth = $(window).width();
    var ResultWidth = (ScreenWidth - PictureWidth) / 2;
    $("#MainPicture").css("left", ResultWidth);
}

This adds a load handler using the one()[docs] method, which simply binds the handler, and unbinds it after the first time it executes.

The handler in this case is your CenterImg() function, so it will be invoked when the image is finished loading.


If there's a chance that the image is cached, and you still want the function to be invoked, you can do this:

$("#MainPicture").attr("src", url)
                 .one('load', CenterImg )
                 .filter(function() { return this.complete; })
                 .load();

function CenterImg() {
    var PictureWidth = $("#MainPicture").width();
    var ScreenWidth = $(window).width();
    var ResultWidth = (ScreenWidth - PictureWidth) / 2;
    $("#MainPicture").css("left", ResultWidth);
}

This way if the image is already loaded, this.complete will return true, and the filter()[docs] method will return a jQuery object with that image so you can manually invoke your .load() handler.

If the image has not yet finished loading, the .filter() will return 0 elements, and the manual load() will have no effect.




回答2:


You don't want it to be synchronous, you want to be able to run your function at the right asynchronous point.

$("#MainPicture").load(CenterImg).attr("src", url);


来源:https://stackoverflow.com/questions/7048157/jquery-synchronous-execute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!