JS 非圖片動(dòng)態(tài)loading效果實(shí)現(xiàn)代碼
2024-05-06 14:10:37
供稿:網(wǎng)友
代碼如下:
首先實(shí)現(xiàn)該功能的js對(duì)象LoadingMsg:
代碼如下:
var Class = {
create: function() {
return function() { this.init.apply(this,arguments); }
}
}
var LoadingMsg = Class.create();
LoadingMsg.prototype = {
init: function(spanId, spanMsg) {
this.intervalID = -10000;
this.spanId = spanId;
this.spanMsg = spanMsg;
this.timespan = 1000;
this.pointNum = 3;
this.initPointMsg = "...";
},
Loading: function() {
var maxLength = this.spanMsg.length + this.pointNum;
var currentSpanMsg = document.getElementById(this.spanId).innerHTML;
if (currentSpanMsg.length < maxLength) {
document.getElementById(this.spanId).innerHTML += ".";
}
else {
document.getElementById(this.spanId).innerHTML = this.spanMsg;
}
},
Start: function() {
document.getElementById(this.spanId).innerHTML = this.spanMsg + this.initPointMsg;
var callObj = this;
this.intervalID = setInterval(function() { callObj.Loading(); }, this.timespan);
},
End: function() {
document.getElementById(this.spanId).innerHTML = "";
clearInterval(this.intervalID);
}
}
關(guān)鍵點(diǎn):
如果把
代碼如下:
var callObj = this;
this.intervalID = setInterval(function() { callObj.Loading(); }, this.timespan);
寫成:
代碼如下:
this.intervalID = setInterval(this.Loading, this.timespan);
在執(zhí)行Loading方法時(shí)則會(huì)報(bào)找不到this.spanMsg的錯(cuò)誤。
因?yàn)樵趕etInterval里的第一個(gè)參數(shù)里的this是windows對(duì)象,而不是LoadingMsg對(duì)象。windows.setInterval嘛。
應(yīng)用該方法:
代碼如下:
<body>
<input type="button" value="Start" onclick="javascript:StartLoading();" />
<span id="spanId" style="color:Red"></span>
<br />
<input type="button" value="End" onclick="javascript:EndLoading();" />
<br /><br />
<script type="text/javascript">
var loadingMsgObj = new LoadingMsg("spanId","loading");
function StartLoading() {
loadingMsgObj.Start();
}
function EndLoading() {
loadingMsgObj.End();
}
</script>
</body>
來源于prototype.js里經(jīng)典創(chuàng)建Js對(duì)象的
代碼如下:
var Class = {
create: function() {
return function() { this.init.apply(this,arguments); }
}
}
var LoadingMsg = Class.create();
在Class.create()的時(shí)候做了2件事,1個(gè)是創(chuàng)建了LoadingMsg的對(duì)象,即var LoadingMsg = function() {};
另外一件事就是調(diào)用LoadingMsg的init方法,初始化LoadingMsg里的靜態(tài)私有變量,相當(dāng)于c#里的構(gòu)造函數(shù)作用。
如果你覺得這很裝逼的話,如果你更喜歡簡(jiǎn)單樸實(shí)的女孩子的話,也可以改寫LoadingMsg對(duì)象:
代碼如下:
var LoadingMsg = function() { };
LoadingMsg.prototype = {
init: function(spanId, spanMsg) {
this.intervalID = -10000;
this.spanId = spanId;
this.spanMsg = spanMsg;