2014-01-07 64 views
0

我發現下面的代碼:格式化JS生成的文本?

var index = 0; 
var text = 'Hardcode'; 
// Here you can put in the text you want to make it type. 
function type() 
{ 
document.getElementById('intro1').innerHTML += text.charAt(index); 
index += 1; 
var t = setTimeout('type()',200); 
// The time taken for each character here is 100ms. You can change it if you want. 
} 

的問題是,文本只適用於很少的一些屬性在我的CSS(標有//):

#intro1 { 
font-family: 'Press Start 2P', cursive; //OK 
font-size: 80px; //OK 
display: block; //? 
text-align: center; //OK 
margin-bottom: auto; 
margin-top: auto; 
top: 50%; 
} 

我試圖讓文本顯示在頁面的中心,但JavaScript忽略了我的放置。 當我將文本直接輸入到HTML中的div時,它工作正常,但是當我用JavaScript做骯髒的工作時,它就搞砸了。

另外,如何添加一個延遲動畫(間隔開始後)?

請幫忙嗎?

+0

要添加延遲使用的setTimeout(的document.getElementById( 'intro1')的innerHTML + = text.charAt(索引)。; index + = 1; var t = setTimeout('type()',200),500 //這是延遲); – Cam

+0

等,所以這是CSS的問題?我沒有看到用JavaScript添加文本會產生什麼影響。 –

+0

你也應該添加一個位置:相對或絕對; – Cam

回答

0

我改變了你撥打type()函數的方式setInterval。希望這可以回答你的問題。

http://jsfiddle.net/fenderistic/eHGK8/

JS

var index = 0; 
var text = 'Hardcode'; 
// Here you can put in the text you want to make it type. 
var f = setTimeout(function() { 
    type() 
}, 1000); 

function type() { 
    document.getElementById('intro1').innerHTML += text.charAt(index); 
    index += 1; 
    var t = setTimeout(function() { 
     type() 
    }, 200); 
    // The time taken for each character here is 100ms. You can change it if you want. 
} 

CSS

html, body { 
margin: 0; 
padding: 0; 
width: 100%; 
height: 100%; 
display: table 
} 
#intro1 { 
display: table-cell; 
text-align: center; 
vertical-align: middle; 
font-family:'Press Start 2P', cursive; 
font-size: 80px; 
} 
+0

但它仍然沒有居中。這是主要問題。 – Claudio

+0

它在我的主窗口中居中,是不是你的問題? – ElliotM

+0

它在小提琴的水平居中,但我也需要它垂直。 – Claudio