我首先开发了一个简单的jQuery动画,然后我创建了一个可重用的jQuery函数,它将执行相同的操作。这是一个演示:http://jsfiddle.net/SpMns/
我的代码工作但不可靠所以:当我点击按钮运行代码时,没有任何反应;单击它两三次将启动动画。为什么第一次不能工作?
请看一下我的日常工作,并告诉我需要纠正哪个方面:
jQuery.fn.busyToggle = function(ImgLoadSrc, marginBottom, opacity, speed,
easing, callback) {
var oDiv = $("<div id='BusyBox'><img src='" + ImgLoadSrc
+ "' alt='Loading...'/><div><em>Loading Wait...</em></div></div>");
if ($("#BusyBox").exists() == false) {
//alert('div not exist');
oDiv.css("background", "-moz-linear-gradient(center top , #F1F2F2 0%, #F1F2F2 100%) repeat scroll 0 0 transparent");
oDiv.css("border-top-left-radius", "5px");
oDiv.css("border-top-right-radius", "5px");
oDiv.css("bottom", "0px");
oDiv.css("font-size", "0.8em");
oDiv.css("font-style", "normal");
oDiv.css("font-weight", "normal");
oDiv.css("left", "50%");
oDiv.css("margin-left", "-45px");
oDiv.css("padding-top", "20px");
oDiv.css("position", "fixed");
oDiv.css("text-align", "center");
oDiv.css("width", "90px");
oDiv.css("height", "50px");
oDiv.css("margin-bottom", "-70px");
oDiv.css("background-repeat", "no-repeat");
oDiv.css("background-position", "center center");
oDiv.data('IsUp', 1)
oDiv.appendTo('body');
}
// i work with jquery data function for achieving toggle behaviour
if (oDiv.data('IsUp') == 1) {
oDiv.data('IsUp', 0);
return this.stop(true).animate({
marginBottom: marginBottom,
opacity: opacity
}, {
queue: false,
duration: speed,
complete: callback
});
}
else {
oDiv.data('IsUp', 1);
return this.stop(true).animate({
marginBottom: marginBottom,
opacity: opacity
}, {
queue: false,
duration: speed,
complete: callback
});
}
};
$(document).ready(function() {
$("#Process").click(function() {
if (flag == 1) {
$('#BusyBox').busyToggle('images/loader.gif', 0, 1, 500, 0, function() {
alert('div visible')
});
flag = 0;
}
else {
$('#BusyBox').busyToggle('images/loader.gif', -70, 0, 500, 0, function(){
alert('div hide')
});
flag = 1;
}
return false;
});
});
第一次运行会导致失败的原因是什么?
答案 0 :(得分:0)
问题在于#busyToggle
中的 this 用法在第一次调用时$('#BusyBox')变成一个空数组,这意味着这个(在#busyToggle中)也是空数组。
更好地解决问题的方法是以这种方式调用busyToggle:
$('#Process').busyToggle('images/loader.gif', 0, 1, 500, 0, function() {
alert('div visible')
});
并在你的函数中使用$('#BusyBox')代替。
您可以在那里找到所有代码:http://jsfiddle.net/ubmCt/8/
P.S:我还在ready函数中添加了以下行,否则它将无法在大多数浏览器中运行
var flag = 1;