嗨即時通訊新的JavaScript和即時通訊嘗試弄清楚如何追加一個字符串後分配的時間量。Javascript自動更改字符串
After 3 secs append string (How)
After 3 secs append string (are)
After 3 secs append string (you)
After 3 secs append string (?)
感謝:d
嗨即時通訊新的JavaScript和即時通訊嘗試弄清楚如何追加一個字符串後分配的時間量。Javascript自動更改字符串
After 3 secs append string (How)
After 3 secs append string (are)
After 3 secs append string (you)
After 3 secs append string (?)
感謝:d
<html>
<head></head>
<body>
<span id="mySpan"></span>
</body>
<script>
setTimeout('document.getElementById("mySpan").innerHTML += "How ";', 3000);
setTimeout('document.getElementById("mySpan").innerHTML += "are ";', 6000);
setTimeout('document.getElementById("mySpan").innerHTML += "you";', 9000);
setTimeout('document.getElementById("mySpan").innerHTML += "?";', 12000);
</script>
</html>
不要將字符串傳遞給'setTimeout'。 – SLaks 2011-05-04 02:38:28
請不要建議將字符串傳遞給'setTimeout'。它是僞裝的「eval」。 – 2011-05-04 02:56:22
使用setTimeout
。
var text = 'How are you ?'.split(' '),
delay = 3000;
function generateCallback(text) {
return function() {
alert(text);
};
}
for (var i=0; i<text.length; i++) {
setTimeout(generateCallback(text[i]), delay*(i+1));
}
由於電流答案的修改,單setInterval
電話可以使用,取消它時,將顯示所有的話:
// s is string to display
// interval is the time in milliseconds between adding words
// id is the id or reference to a DOM element to display s in
function staggerDisplay(s, interval, id) {
var el = typeof id == 'string'? document.getElementById(id) : id;
var sBits = s.split(' ');
var numWords = sBits.length;
var i = 0;
var intervalRef = setInterval(
function() {
if (i < numWords) {
el.innerHTML += ' ' + sBits[i++];
} else {
clearInterval(intervalRef);
}
}, interval);
}
請注意@SLaks'評論**不要**將字符串傳遞給'setTimeout'。它是僞裝的「eval」。 – 2011-05-04 02:55:41